<?php
namespace Addons\QyWechat\Controller\Admin;

use Models\BaseModel as Model;
use Session;
use Addons\QyWechat\Helper;
use Addons\QyWechat\Services\QyWechatApi;
use Addons\QyWechat\Services\ProvidersApi;
use Addons\QyWechat\Config\app; 
use Addons\ShopCollection\Controller\Api\SyncPointBigData;

class Externalcontact extends BaseAdmin
{	
    public function manages(){
		return $this->show();
	}
	 
	public function customer_list(){ 
		if(!$_GET["is_set"]){ 
			return $this->show("Admin/Externalcontact/customer_lists");
		}
		$wid = Session::get('wid');	
		$r_type = Session::get('r_type');	
		$qyCustomer = new Model('qy_externalcontact_list');
		// $where['wid'] = $wid;
		$h = Helper::getInstance(); 
		$etTagArr = $h->get_et_tags($wid);
		$addWayArr = $h->add_way_arr();
		$sql = "select * from qvmh_qy_externalcontact_list where wid={$wid}";
		$r_user_id_arr = $h->get_check_range('cuscontact_customerlist');
		// if($r_user_id_arr){
		// 	foreach ($r_user_id_arr as $key => $value) {
		// 		$sql .= " and user_id={$value}";
		// 	}
		// }
		$user_id_arr = [];
		if(\Request::get()){
			if($_GET["price_min"]!=""){
				$price_min = $_GET["price_min"];
				$sql .= " and name like '%{$price_min}%'";
			}
			if(trim($_GET["qyuser"])!=""){
				$qyuser = $_GET['qyuser'];
				$user_id_arr = array_column((new Model('qy_user_list'))->field('id')->where(['wid'=>$wid,'name@~'=>$_GET["qyuser"]])->list_all_array(), 'id');
			}
			if($_GET["tags"]!=""){
				$tags = explode(",", $_GET["tags"]);
				foreach ($tags as $key => $value) {
					$sql .= " and tags like '%\"{$value}\"%'";
				}
			}
			if($_GET["addTime"]!=""){
				$ktime = strtotime(substr($_GET["addTime"],0,10));
				$jtime = strtotime(substr($_GET["addTime"],-10));
				$sql .= " and createtime < {$jtime}";
				$sql .= " and createtime > {$ktime}";
			}
			if($_GET["channe2"]!=""){
				$add_wy = $_GET["channe2"];
				$sql .= " and add_way = {$add_wy}";
			}
			if($_GET["channe3"]!=""){
				$gender = $_GET["channe3"];
				$sql .= " and gender = {$gender}";
			}
			if($_GET["channe4"]!=""){
				$status = $_GET["channe4"];
				if($status == 0){
					$sql .= " and status = {$status}";
				}else{
					$sql .= " and (status = 1 or status = 2)";
				}
			}
		}

		//按员工筛选
		$id_arr = [];
		if($r_user_id_arr && $user_id_arr){
			$id_arr = array_intersect($r_user_id_arr,$user_id_arr);
		}else{
			$id_arr = array_merge($id_arr,$r_user_id_arr,$user_id_arr);
		}
		if($id_arr){
			$sql .= " and user_id in (".implode(',', $id_arr).")";
		}

		// echo $sql;die;
		$sql .= " ORDER BY createtime DESC";
		$p = new \Pagination();	
		$res = $p->sql_list($sql);
		// $res = db_query($res);
		$count = db_query($count);
		foreach($res as $key=>$value){
			$res[$key]["tags"] = json_decode($value["tags"],1);
			$res[$key]["user"] = (new Model('qy_user_list'))->find($value["user_id"]);
			$sql = db_query("select max(msgtimes) as lastTime from qvmh_qy_chat_data where wid = {$wid} and is_group = 0 and (fromid = '{$res[$key]["user"]->userid}' and tolist like '%{$value['external_userid']}%') or(fromid = '{$value['external_userid']}' and tolist like '%{$res[$key]["user"]->userid}%')");
			$res[$key]["time"] = '-';
			if((int)$sql[0]['lastTime']){
				$res[$key]["time"] = date("Y-m-d H:i:s", $sql[0]['lastTime']);
			}
		}
		$this->assign("p", $p);
		$this->assign("P", $GLOBALS['P']);
		$this->assign("res", $res);
		$this->assign("r_type", $r_type);
		$this->assign("addWayArr", $addWayArr);
		$this->assign("etTagArr", $etTagArr);
		return $this->show();
	}
	
	public function customer_info(){
		$wid = Session::get('wid');
		$r_user_id = Session::get('r_user_id');
		$etId = \Request::get(1);
		$message = (new Model("qy_messageset"))->find(["wid"=>$wid]);
		$et = (new Model('qy_externalcontact_list'))->find($etId);
		$et->tags = json_decode($et->tags,1);
		$et->remark_mobiles = implode(",",json_decode($et->remark_mobiles,1));
		$et->user = (new Model('qy_user_list'))->find(['id'=>$et->user_id]);
		if(!$et->id){
			die('未知客户');
		}
		if($et->user_id != $r_user_id){
			$et->r_user_id = $r_user_id;
		}
		$qyEtGroupchat = (new Model('qy_et_groupchat'))->where(['wid'=>$wid])->list_all();
		$groupchat = [];
		foreach($qyEtGroupchat as $qyetgroupchat){
			$member_list = json_decode($qyetgroupchat->member_list,1);
			foreach($member_list as $member){
				if($member['userid'] == $et->external_userid){
					$groupchat[] = $qyetgroupchat;
				}
			}
		}
		$template_event = (new Model('qy_template_event'))->where(['wid'=>$wid,'status'=>1])->list_all();
		/**$follow_user = json_decode($et->follow_user,1);
		foreach($follow_user as $k=>$v){
			$user = (new Model('qy_user_list'))->find(['wid'=>$wid,'userid'=>$v['userid']])->get_model_array();
			$follow_user[$k]['user'] = $user;
		}*/
		$etAll = (new Model('qy_externalcontact_list'))->where(['id@!='=>$etId,'wid'=>$wid,'external_userid'=>$et->external_userid])->list_all();
		foreach($etAll as $k=>$v){
			$etAll[$k]->tags = json_decode($v->tags,1);
			$etAll[$k]->remark_mobiles = implode(",",json_decode($v->remark_mobiles,1));
			$etAll[$k]->custom = json_decode($v->custom_information,1);
			$etAll[$k]->user = (new Model('qy_user_list'))->find(['id'=>$v->user_id]);
			if($r_user_id != $v->user_id){
				$etAll[$k]->r_user_id = $r_user_id;
			}
			$data = (new Model('user_fields'))->where(['wid'=>$wid,'user_id'=>$v->id])->list_all();
            $fis = (new Model("qy_custom_fields"))->where(["wid"=>$wid])->order('orders asc')->list_all();
            foreach ($fis as $keys => $values) {
                foreach ($data as $key => $user_v) {
                    if($user_v->fields_id == $values->id){
                        $fis[$keys]->is_x = 1;
                        $fis[$keys]->contents = $user_v->content;
                    }
                }
                $fis[$keys]->content = json_decode($values->content,1);
                $fis[$keys]->user_id = $v->id;
                if($r_user_id != $v->user_id){
					$fis[$keys]->r_user_id = $r_user_id;
				}
                $fis[$keys]->wid = $wid;
            }
            $etAll[$k]->fields = json_encode($fis);
		}
		$qyEtDynamic = (new Model('qy_et_dynamic'))->where(['wid'=>$wid,'external_userid'=>$et->external_userid])->order('ctime desc')->list_all_array();
		$etDynamic = [];
		foreach($qyEtDynamic as $qyetdynamic){
			$etDynamic[date('m_d',$qyetdynamic['ctime'])][] = $qyetdynamic;
		}
		$h = Helper::getInstance();
		$etTagArr = $h->get_et_tags($wid);
		$addWayArr = $h->add_way_arr();
		$user_con = json_decode($et->custom_information,1);
		// $larel = (new Model('qy_level_manager'))->where(["wid"=>$wid])->list_all();
		// $larel_one = (new Model('qy_level_manager'))->find(["wid"=>$wid,"id"=>$et->level_manager_id]);
		// foreach ($larel as $key => $value) {
		// 	if($value->name != $larel_one->name){
		// 		$arr[] = $value;
		// 	}
		// }
		// $this->assign("larel_one", $larel_one);
		// $this->assign("arr", $arr);
		$user_fields = (new Model('user_fields'))->where(['wid'=>$wid,'user_id'=>$etId])->list_all();
        $fields = (new Model("qy_custom_fields"))->where(["wid"=>$wid])->order('orders asc')->list_all();
        foreach ($fields as $keys => $values) {
            foreach ($user_fields as $key => $user_v) {
                if($user_v->fields_id == $values->id){
                    $fields[$keys]->is_x = 1;
                    $fields[$keys]->contents = $user_v->content;
                }
            }
            if($et->user_id != $r_user_id){
				$fields[$keys]->r_user_id = $r_user_id;
			}
            $fields[$keys]->content = json_decode($values->content,1);
            $fields[$keys]->user_id = $etId;
            $fields[$keys]->wid = $wid;
        }
        $et->fields = json_encode($fields);
		$this->assign("et", $et);
		$this->assign("template_event", $template_event);
		$this->assign("user_con", $user_con);
		$this->assign("fields", $fields);
		$this->assign("etAll", $etAll);
		$this->assign("r_user_id", $r_user_id);
		$this->assign("message", $message);
		$this->assign("etTagArr", $etTagArr);
		$this->assign("addWayArr", $addWayArr);
		$this->assign("groupchat", $groupchat);
		$this->assign("etDynamic", $etDynamic);
		$this->assign("h", $h);
		return $this->show();
	}

	  public function upd_user_fields(){
        setApi();
        $wid = $_POST["wid"];
        $user_id = $_POST["user_id"];
        $id = $_POST["id"];
        $content = $_POST["content"];
        $user_fields = (new Model('user_fields'))->find(['wid'=>$wid,'user_id'=>$user_id,'fields_id'=>$id]);
        if(!$user_fields->id){
            $user_fields = new Model('user_fields');
            $user_fields->wid = $wid;
            $user_fields->user_id = $user_id;
            $user_fields->fields_id = $id;
        }
        $user_fields->content = $content;
        if($user_fields->save()){
            sendSuccess("修改成功");
        }
        sendError("修改失败");
    }
	/*
	*添加动态
	*/
	public function add_dynamic_record(){
		setApi();
		$wid = Session::get('wid');
		$et_id = $_POST['et_id'];
		$externalcontact = (new Model('qy_externalcontact_list'))->find($et_id);
		$user_id = $_POST['user_id'];
		$dynamic_record = new Model('qy_et_dynamic');
		$dynamic_record->wid  = $wid;
		$dynamic_record->external_userid = $externalcontact->external_userid;
		$dynamic_record->user_id  = $user_id;
		$dynamic_record->glian_id = $_POST['contentEventId'];	
		$dynamic_record->content  = $_POST['eventType'] == 1 ? $_POST['content'] : $_POST['contentEvent'];
		$dynamic_record->type  = 7;
		$content_sup =  isset($_POST['test2']) ? ['image'=>$_POST['test2']] : '';
		if($content_sup != ''){
			$dynamic_record->content_sup = json_encode($content_sup,320);
		}
		
		$dynamic_record->ctime  = time();
		if($dynamic_record->save()){
			$dynamic_record->ztime = date("m_d",$dynamic_record->ctime);
			$dynamic_record->jtime = date("Y-m-d H:i:s",$dynamic_record->ctime);
			$dynamic_record->title = $dynamic_record->glian_id ? Helper::getInstance()->get_template_event($dynamic_record->glian_id)['name'] : '跟进记录';
			$dynamic_record->avatar =  $externalcontact->avatar;
			$dynamic_record->et_name =  $externalcontact->name;
			sendSuccess('添加成功',$dynamic_record);
		}
		sendError('添加失败');
	}
	/*
	*添加模板标签
	*/
	public function add_template_even(){
		setApi();
		$wid = Session::get('wid');
		$name = $_POST['event'];
		$type = $_POST['type'];
		$template_event = new Model('qy_template_event');
		switch ($type) {
			case '1':    //添加
				$template_event->wid = $wid;
				$template_event->name = $name;
				$template_event->status = 1;
				if($template_event->save()){
					sendSuccess('添加成功',$template_event);
				}
				break;
			case '2':    //修改
				$template_event->find($_POST['id']);
				$template_event->name = $name;
				if($template_event->save()){
					sendSuccess('修改成功',$template_event);
				}
				break;
			case '3':    //删除
				$template_event->find($_POST['id']);
				$template_event->status = 0;
				if($template_event->save()){
					sendSuccess('删除成功',$template_event);
				}
				break;
		}
		
		sendError('操作失败');
	}

	public function update_tag(){
		setApi();
		$title = \Request::post('title');
		$type = \Request::post('type');
		$id = \Request::post('id');
		$larel_name = \Request::post('larel_name');
		$name = \Request::post('name');
		$et = (new Model('qy_externalcontact_list'))->find($id);
		$wid = $et->wid;
		$qyConfig = (new Model('qy_wechat_config'))->find(['wid'=>$wid]);
		// $replyConfig = (new Model('qy_reply_config'))->find(['wid'=>$wid]);
		$replyConfig = Helper::getInstance()->get_message_send_config($wid);
		$app = QyWechatApi::getInstance()->get_qy_agent_app($qyConfig->corp_id,$replyConfig->agent_id,$replyConfig->secret);
		$accessToken = $app->access_token;
        $token = $accessToken->getToken()['access_token'];
		if($et->custom_information == ""){
			$arr = ['qq'=>null,'birthday'=>null,'age'=>null,'email'=>null,'weibo'=>null,'address'=>null,"mobile"=>null];
			$et->custom_information = json_encode($arr,320);
			$et->save();
		}
		$desc = json_decode($et->custom_information,1);
		foreach ($desc as $key => $value) {
			if($key == $type && $title == $value){
				sendError($classa."未修改");
			}else if($key == $type){
				$desc[$key] = $title;
			}
		}
		if($larel_name){
			$et->level_manager_id = $larel_name;
			$et->save();
		}
		if($type == "mobiles"){
			$mobile = explode(",", $title);
            foreach ($mobile as $key => $value) {
                if(strlen($value) != 11){
                    sendError("请输入正确的11位手机号码");
                }
            }
			$user = (new Model("qy_user_list"))->find(["id"=>$et->user_id]);
			$body = \HttpCurl::post(
			   	"https://qyapi.weixin.qq.com/cgi-bin/externalcontact/remark?access_token=".$token,
			    json_encode([
			      	"userid"=>$user->userid,
	   				"external_userid"=>$et->external_userid,
	   				"remark_mobiles"=>$mobile
			    ])
			 );
	  		$resp_arr = json_decode($body, 1);
	        if($resp_arr["errmsg"] == "ok"){
	        	$mobiles = json_encode(explode(",", $title),320);
	        	$et->remark_mobiles = $mobiles;
	        }else{
				sendError("手机号码格式不合法");
	        }
		}else if($type == "description"){
			if($et->description == $title){
				sendError($name."未修改");
			}
			$et->description = $title;
		}
		$et->custom_information = json_encode($desc,320);
		$et->save();
		sendSuccess($name.'修改成功');
	}
	
	public function et_tag_set(){
		$wid = Session::get('wid');
		$etTagArr = (new Model('qy_externalcontact_tag'))->where(['wid'=>$wid])->list_all_array();
		/**foreach($etTagArr as $v){
			foreach(json_decode($v['tags'],1) as $v2){
				$newEtTagArr[$v['group_name'].'_'.$v2['name']] = $v2['id'];
			}
		}*/
		$etId = \Request::get(1);
		if($etId){
			$et = (new Model('qy_externalcontact_list'))->find($etId);
			$etTags = json_decode($et->tags,1);
		}else{
			die('未知客户');
		}
		$qyUser = (new Model('qy_user_list'))->find(['id'=>$et->user_id]);
		if(is_post()){
			setApi();
			$checkTag = $_POST['tags'];
			$add_tag = [];
			$remove_tag = [];
			foreach($checkTag as $v){
				if(!in_array($v,$etTags)){
					$add_tag[] = $v;
				}
			}
			foreach($etTags as $v){
				if(!in_array($v,$checkTag)){
					$remove_tag[] = $v;
				}
			}
			if(!$add_tag && !$remove_tag){
				sendError('您未做任何修改');
			}
			$QyWechatApi = QyWechatApi::getInstance();
			$param = [
				'userid' => $qyUser->userid,
				'external_userid' => $et->external_userid,
				'add_tag' => $add_tag,
				'remove_tag' => $remove_tag
			];
			$editEtTagRes = $QyWechatApi->edit_et_tag($param);
			if($editEtTagRes['errcode'] == 0){
				$et->tags = json_encode($checkTag,320);
				if($et->save()){
					sendSuccess('操作成功');
				}else{
					sendError('数据库操作失败');
				}
			}else{
				sendError('操作失败'.$editEtTagRes['errmsg']);
			}			
		}
		$this->assign("etTagArr", $etTagArr);
		$this->assign("etTags", $etTags);
		return $this->show();
	}
	
	public function tag_manage(){
		$wid = Session::get('wid');
		
		$eTag = new Model('qy_externalcontact_tag');
		$tj = new \SampleModel('tj');
		$where = $tj->load_array_from_get();
		//name 模糊查询
		if(trim($where['group_name'])!=''){
			$where['group_name@~'] = $where['group_name'];	
		}
		unset($where['group_name']);
		$where['wid'] = $wid;
		$p = new \Pagination();		
		$res = $p->model_list($eTag->where($where)->order('id'));
		foreach($res as $k=>$v){
			$res[$k]->tags = json_decode($v->tags,1);
		}		
		$this->assign('tj', $tj);
		$this->assign("p", $p);
		$this->assign("P", $GLOBALS['P']);
		$this->assign("res", $res);
		return $this->show();
	}
	
	public function add_tag(){
		$wid = Session::get('wid');
		$group_id = $_POST['group_id'];
		setApi();
		$QyWechatApi = QyWechatApi::getInstance();
		$tag_name = $_POST['tag_name'];
		$param = [
			'group_id' => $group_id,
			'tag' => [
				['name'=>$tag_name],
			]
		];
		$addTagRes = $QyWechatApi->add_corp_tag($param);
		if($addTagRes['errcode'] == 0){
			$tag_group = $addTagRes['tag_group'];
			$qyTag = (new Model('qy_externalcontact_tag'))->find(['wid'=>$wid,'group_id'=>$tag_group['group_id']]);
			$qyTags = json_decode($qyTag->tags,1);
			foreach($tag_group['tag'] as $tag){
				array_push($qyTags,$tag);
			}
			$qyTag->tags = json_encode($qyTags,320);
			if($qyTag->save()){
				sendSuccess('操作成功');
			}else{
				sendError('数据库操作失败');
			}
		}else{
			sendError('操作失败'.$addTagRes['errmsg']);
		}
	}
	
	public function edit_tag(){
		$wid = Session::get('wid');
		$id =  \Request::get('id');
		$tagid =  \Request::get('tagid');
		$qyTag = (new Model('qy_externalcontact_tag'))->find(['wid'=>$wid,'id'=>$id]);
		$tagArr = json_decode($qyTag->tags,1);
		$tagName = '';
		foreach($tagArr as $k=>$v){
			if($v['id'] == $tagid){
				$tagName = $v['name'];
			}
		}
		if(is_post()){
			setApi();
			$QyWechatApi = QyWechatApi::getInstance();
			$param = [
				'id' => $tagid,
				'name' => $_POST['tag_name']
			];
			$editTagRes = $QyWechatApi->edit_corp_tag($param);
			if($editTagRes['errcode'] == 0){
				foreach($tagArr as $k=>$v){
					if($v['id'] == $tagid){
						$tagArr[$k]['name'] = $_POST['tag_name'];
					}
				}
				$qyTag->tags = json_encode($tagArr);
				$qyTag->save();
				sendSuccess('操作成功');
			}else{
				sendError('操作失败'.$editTagRes['errmsg']);
			}
		}
		$this->assign("tagName", $tagName);
		return $this->show();
	}
	
	public function del_tag(){
		$wid = Session::get('wid');
		if(is_post()){
			setApi();
			$QyWechatApi = QyWechatApi::getInstance();
			$id = $_POST['id'];
			$tagid = $_POST['tagid'];
			$qyTag = (new Model('qy_externalcontact_tag'))->find(['wid'=>$wid,'id'=>$id]);
			$param = [
				'tag_id' => $tagid,
				//'group_id' => $qyTag->group_id
			];
			$delTagRes = $QyWechatApi->del_corp_tag($param);
			if($delTagRes['errcode'] == 0){
				$tagArr = json_decode($qyTag->tags,1);
				foreach($tagArr as $k=>$v){
					if($v['id'] == $tagid){
						unset($tagArr[$k]);
					}
				}
				$qyTag->tags = json_encode($tagArr);
				$qyTag->save();
				//标签组下所有的标签均被删除 则删除组
				if(!count(json_decode($qyTag->tags,1))){
					$qyTag->delete();
				}
				sendSuccess('操作成功');
			}else{
				sendError('操作失败'.$delTagRes['errmsg']);
			}
		}
	}
	
	public function add_tag_group(){
		$wid = Session::get('wid');
		if(is_post()){
			setApi();
			$arr = explode("&",$_POST["params"]);
			foreach ($arr as $key => $value) {
				$arrone[]  = substr($value,6);
			}
			$QyWechatApi = QyWechatApi::getInstance();
			$group_names = array_shift($arrone);
			if($group_names == ""){
				sendError('必填项不能为空');
			}
			for ($i=0; $i <count($arrone) ; $i++) { 
				if($arrone[$i] == ""){
					sendError('必填项不能为空');
				}
				$param = [
					'group_name' => $group_names,
					'tag' => [
						['name'=>$arrone[$i]],
					]
				];
				$addTagRes[] = $QyWechatApi->add_corp_tag($param);
			}
			foreach($addTagRes as $key=>$value){
				$tag_group_arr[] = $value['tag_group'];
			}
			foreach ($tag_group_arr as $key => $value) {
				$qyTags[] = $value['tag'][0];
			}
			$group_id = $tag_group_arr[0]['group_id'];
			$errcode = $tag_group_arr[0]['errcode'];
			$errmsg = $tag_group_arr[0]['errmsg'];
			$group_name = $tag_group_arr[0]['group_name'];
			$create_time = $tag_group_arr[0]['create_time'];
			$order = $tag_group_arr[0]['order'];
			$deleted = $tag_group_arr[0]['deleted'];
			if($errcode == 0){
				$tag_group = array('group_id'=>$group_id,'group_name'=>$group_name,'create_time'=>$create_time,'order'=>$order,'deleted'=>$deleted);
				$qyTag = new Model("qy_externalcontact_tag");
				$qyTag->wid = $wid;
				$qyTag->group_id = $tag_group['group_id'];
				$qyTag->group_name = $tag_group['group_name'];
				$qyTag->create_time = $tag_group['create_time'];
				$qyTag->order = $tag_group['order'];
				$qyTag->deleted = $tag_group['deleted'];
				$qyTag->tags = json_encode($qyTags,320);
				if($qyTag->save()){
					sendSuccess('操作成功');
				}else{
					sendError('数据库操作失败');
				}
			}else{
				sendError('操作失败'.$errmsg);
			}
		}
		return $this->show();
	}
	public function update_name(){
		$wid = Session::get('wid');
		$group_id = \Request::get('group_id');
		$qyTag = (new Model("qy_externalcontact_tag"))->find(['wid'=>$wid,'group_id'=>$group_id]);
		if(is_post()){
			setApi();
			$QyWechatApi = QyWechatApi::getInstance();
			$title = $_POST["title"];
			$param = [
				'id' => $qyTag->group_id,
				'name' => $title,
			];
			$edit_tag = $QyWechatApi->edit_corp_tag($param);
			$qyTag->group_name = $title;
			$qyTag->save();
			sendSuccess('操作成功');
		}
		$this->assign("qyTag",$qyTag);
		return $this->show();
	}
	public function del_tag_group(){
		$wid = Session::get('wid');
		if(is_post()){
			setApi();
			$QyWechatApi = QyWechatApi::getInstance();
			$group_id = $_POST['group_id'];
			$param = [
				'group_id' => $group_id,
			];
			$delTagRes = $QyWechatApi->del_corp_tag($param);
			if($delTagRes['errcode'] == 0){
				(new Model('qy_externalcontact_tag'))->delete(['wid'=>$wid,'group_id'=>$group_id]);
				sendSuccess('操作成功');
			}else{
				sendError('操作失败'.$delTagRes['errmsg']);
			}
		}	
	}
	
	public function tongbu_tag(){
		setApi();
		$wid = Session::get('wid');
		$QyWechatApi = QyWechatApi::getInstance();
		$tagRes = $QyWechatApi->get_corp_tag_list();
		if($tagRes['errcode'] == 0){
			$tagList = $tagRes['tag_group'];
			(new Model('qy_externalcontact_tag'))->delete(['wid'=>$wid]);
			foreach($tagList as $tag){
				$eTag = new Model('qy_externalcontact_tag');
				$eTag->wid = $wid;
				$eTag->group_id = $tag['group_id'];
				$eTag->group_name = $tag['group_name'];
				$eTag->create_time = $tag['create_time'];
				$eTag->order = $tag['order'];
				$eTag->deleted = $tag['deleted'];
				$eTag->tags = json_encode($tag['tag'],320);
				$eTag->save();
			}
		}
		sendSuccess('已同步');
	}
	

	// public function tongbu_customer(){
	// 	set_time_limit(0);
	// 	setApi();
	// 	$wid = Session::get('wid');
	// 	$qyConfig = (new Model('qy_wechat_config'))->find(['wid'=>$wid]);
	// 	$QyWechatApi = QyWechatApi::getInstance();
	// 	$etApp = $QyWechatApi->get_qy_app($qyConfig->corp_id,$qyConfig->externalcontact_secret);
	// 	$ProvidersApi = ProvidersApi::getInstance();
	// 	$work = $ProvidersApi->get_work($qyConfig->corp_id);
	// 	//获取通讯录列表
	// 	$qyUser = (new Model('qy_user_list'))->where(['wid'=>$wid])->list_all();
	// 	$customer_list_arr = [];
	// 	foreach($qyUser as $qyuser){
	// 		//获取客户列表
	// 		$customer_list_res = $etApp->external_contact->list($qyuser->userid);
	// 		$customer_list_res2 = $work->external_contact->list($qyuser->userid);
	// 		if($customer_list_res['errcode'] == 0 && $customer_list_res2['errcode'] == 0 && count($customer_list_res['external_userid']) && count($customer_list_res2['external_userid'])){
	// 			$customer_list_arr[$qyuser->id] = [$customer_list_res['external_userid'],$customer_list_res2['external_userid']];
	// 		}
	// 	}
	// 	//导数据
	// 	foreach($customer_list_arr as $user_id => $customer_list){
	// 		foreach($customer_list[0] as $customer){
	// 			//获取客户详情
	// 			$customer_info_res = $etApp->external_contact->get($customer);
	// 			if($customer_info_res['errcode'] == 0){
	// 				$customer_info = $customer_info_res;
	// 				$qyCustomer = (new Model('qy_externalcontact_list'))->find(['wid'=>$wid,'user_id'=>$user_id,'external_userid'=>$customer_info['external_contact']['external_userid']]);
	// 				$qyUserById = (new Model('qy_user_list'))->find(['id'=>$user_id]);

	// 				$user = '';
	// 				$tags = [];
	// 				foreach($customer_info['follow_user'] as $followuser){
	// 					if($qyUserById->userid == $followuser['userid']){
	// 						$user = $followuser;
	// 						foreach($followuser['tags'] as $ftag){
	// 							$tags[] = $ftag['tag_id'];
	// 						}
	// 					}
	// 				}						
	// 				$qyCustomer->wid = $wid;
	// 				$qyCustomer->external_userid = $customer_info['external_contact']['external_userid'];
	// 				$qyCustomer->name = Helper::getInstance()->filterEmoji($customer_info['external_contact']['name']);
	// 				$qyCustomer->avatar = $customer_info['external_contact']['avatar'];
	// 				$qyCustomer->type = $customer_info['external_contact']['type'];
	// 				$qyCustomer->gender = $customer_info['external_contact']['gender'];
	// 				$qyCustomer->unionid = $customer_info['external_contact']['unionid'];
	// 				$qyCustomer->position = $customer_info['external_contact']['position'];
	// 				$qyCustomer->corp_name = $customer_info['external_contact']['corp_name'];
	// 				$qyCustomer->corp_full_name = $customer_info['external_contact']['corp_full_name'];
	// 				$qyCustomer->external_profile = json_encode($customer_info['external_contact']['external_profile']);
	// 				$qyCustomer->user_id = $user_id;
	// 				$qyCustomer->remark = $user['remark'];
	// 				$qyCustomer->description = $user['description'];
	// 				$qyCustomer->createtime = $user['createtime'];
	// 				$qyCustomer->tags_info = json_encode($user['tags']);
	// 				$qyCustomer->tags = json_encode($tags);
	// 				$qyCustomer->remark_corp_name = $user['remark_corp_name'];
	// 				$qyCustomer->remark_mobiles = $user['remark_mobiles'];
	// 				$qyCustomer->add_way = $user['add_way'];
	// 				$qyCustomer->oper_userid = $user['oper_userid'];
	// 				$qyCustomer->state = $user['state'];
	// 				$qyCustomer->status = 0;
	// 				$qyCustomer->save();
										
	// 			}
	// 		}
	// 		foreach($customer_list[1] as $customer){
	// 			//获取客户详情
	// 			$customer_info_res = $work->external_contact->get($customer);
	// 			if($customer_info_res['errcode'] == 0){
	// 				$customer_info = $customer_info_res;
	// 				$qyCustomer = (new Model('qy_providers_externalcontact_list'))->find(['wid'=>$wid,'user_id'=>$user_id,'external_userid'=>$customer_info['external_contact']['external_userid']]);
	// 				$qyUserById = (new Model('qy_user_list'))->find(['id'=>$user_id]);
					
	// 				$user = '';
	// 				$tags = [];
	// 				foreach($customer_info['follow_user'] as $followuser){
	// 					if($qyUserById->userid == $followuser['userid']){
	// 						$user = $followuser;
	// 						foreach($followuser['tags'] as $ftag){
	// 							$tags[] = $ftag['tag_id'];
	// 						}
	// 					}
	// 				}						
	// 				$qyCustomer->wid = $wid;
	// 				$qyCustomer->external_userid = $customer_info['external_contact']['external_userid'];
	// 				$qyCustomer->name = Helper::getInstance()->filterEmoji($customer_info['external_contact']['name']);
	// 				$qyCustomer->avatar = $customer_info['external_contact']['avatar'];
	// 				$qyCustomer->type = $customer_info['external_contact']['type'];
	// 				$qyCustomer->gender = $customer_info['external_contact']['gender'];
	// 				$qyCustomer->unionid = $customer_info['external_contact']['unionid'];
	// 				$qyCustomer->position = $customer_info['external_contact']['position'];
	// 				$qyCustomer->corp_name = $customer_info['external_contact']['corp_name'];
	// 				$qyCustomer->corp_full_name = $customer_info['external_contact']['corp_full_name'];
	// 				$qyCustomer->external_profile = json_encode($customer_info['external_contact']['external_profile']);
	// 				$qyCustomer->user_id = $user_id;
	// 				$qyCustomer->remark = $user['remark'];
	// 				$qyCustomer->description = $user['description'];
	// 				$qyCustomer->createtime = $user['createtime'];
	// 				$qyCustomer->tags_info = json_encode($user['tags']);
	// 				$qyCustomer->tags = json_encode($tags);
	// 				$qyCustomer->remark_corp_name = $user['remark_corp_name'];
	// 				$qyCustomer->remark_mobiles = $user['remark_mobiles'];
	// 				$qyCustomer->add_way = $user['add_way'];
	// 				$qyCustomer->oper_userid = $user['oper_userid'];
	// 				$qyCustomer->state = $user['state'];
	// 				$qyCustomer->status = 0;
	// 				$qyCustomer->save();
										
	// 			}
	// 		}
	// 	}
	// 	sendSuccess('已同步');
	// }
	public function ceshi(){
		set_time_limit(0);
		setApi();
		$h = Helper::getInstance();
		$wid = Session::get('wid');
		$qyConfig = (new Model('qy_wechat_config'))->find(['wid'=>$wid]);
		// $QyWechatApi = QyWechatApi::getInstance();
		// $etApp = $QyWechatApi->get_qy_app($qyConfig->corp_id,$qyConfig->externalcontact_secret);
		//获取通讯录列表->order('id asc')->limit(28000,1000)
		$qyUser = (new Model('qy_user_list'))->field('id,userid')->where(['wid'=>$wid,'is_del@!='=>1])->order('id asc')->list_all_array();
		$threadNum = app::$thread_level * 100;
		$totalQyUser = count($qyUser);
		$cardinalty = ceil($totalQyUser/$threadNum);
		$qyUsers = array_chunk($qyUser, $cardinalty);
		$mh = curl_multi_init();
		$conn = [];
		$res = [];
		$url = $h->get_http_server_name()."/Addons/QyWechat/Admin/Externalcontact/ceshi2-".$wid.".html";

		for ($i=0;$i<count($qyUsers);$i++) {
		     $data = http_build_query($qyUsers[$i]);
		     $conn[$i]=curl_init($url);
		      curl_setopt($conn[$i],CURLOPT_RETURNTRANSFER,1); //如果成功只将结果返回，不自动输出任何内容
		      curl_setopt($conn[$i],CURLOPT_TIMEOUT,0);
		      curl_setopt($conn[$i], CURLOPT_POSTFIELDS, $data); //post 传参
		      curl_multi_add_handle ($mh,$conn[$i]);
		}
		do { $n=curl_multi_exec($mh,$active); }
		while ($active);

		$result = true;
		for ($i=0;$i<count($departmentLists);$i++) {
		      $res[$i]=curl_multi_getcontent($conn[$i]);
		      // echo microtime()."<br>";
			// $res = curl_multi_getcontent($conn[$i]);
		      curl_close($conn[$i]);
		      if($res[$i]['code'] == 'error'){
				$result = false;
		      }
		}
		if($result = false){
			sendError('11');
		}
		sendSuccess('已同步');
		
	} 
	public function ceshi2(){
		set_time_limit(0);
		setApi();
		$res = json_encode([
        	'code' => 'ok',
        	'msg'=>''
        ]);
		$wid = $this->wid;
		$qyConfig = (new Model('qy_wechat_config'))->find(['wid'=>$wid]);
		$QyWechatApi = QyWechatApi::getInstance();
		$etApp = $QyWechatApi->get_qy_app($qyConfig->corp_id,$qyConfig->user_secret);
		$data = $_POST;
		$customer_list_arr = [];
		$datas = [];
		$sql = "INSERT INTO qvmh_qy_externalcontact_list ( wid, external_userid, name,avatar,type,gender,unionid,position,corp_name,corp_full_name,external_profile,user_id,remark,description,createtime,tags_info,tags,remark_corp_name,remark_mobiles,add_way,oper_userid,state) VALUES";
		foreach($data as $user){
			$user_id = $user['id'];
			$customer_list_res = $QyWechatApi->get_et_list($user['userid'],$wid);
			if(count($customer_list_res)){
				foreach ($customer_list_res as $customer_list => $customer_info) {
					$tags = [];
					$users = $customer_info['follow_info'];
					$tags = $customer_info['follow_info']['tag_id'];
					$wid = $wid;
					$external_userid = $customer_info['external_contact']['external_userid'];
					$name = Helper::getInstance()->filterEmoji($customer_info['external_contact']['name'])??null;
					$avatar = $customer_info['external_contact']['avatar']??null;
					$type = $customer_info['external_contact']['type']??null;
					$gender = $customer_info['external_contact']['gender']??null;
					$unionid = $customer_info['external_contact']['unionid']??null;
					$position = $customer_info['external_contact']['position']??null;
					$corp_name = $customer_info['external_contact']['corp_name']??null;
					$corp_full_name = $customer_info['external_contact']['corp_full_name']??null;
					$external_profile = json_encode($customer_info['external_contact']['external_profile'],320);
				    $external_profile = null;
					$remark = Helper::getInstance()->filterEmoji($users['remark'])??null;
					$description = $users['description']??null;
					$createtime = $users['createtime']??null;
					$tags_info = json_encode($users['tag_id'],320);
					$tags = json_encode($tags,320);
					$remark_corp_name = $users['remark_corp_name']??null;
					$remark_mobiles = json_encode($users['remark_mobiles'],320);
					$add_way = $users['add_way']?:0;
					$oper_userid = $users['oper_userid']??null;
					$state = $users['state']??null;
					$datas[] = "($wid,'{$external_userid}','{$name}','{$avatar}',{$type},{$gender},'{$unionid}','{$position}','{$corp_name}','{$corp_full_name}','{$external_profile}',{$user_id},'{$remark}','{$description}','{$createtime}','{$tags_info}','{$tags}','{$remark_corp_name}','{$remark_mobiles}',{$add_way},'{$oper_userid}','{$state}')";
				}
			}
		}
		if(!count($datas))return $res;
		$sql .= implode(',', $datas);
		$sql .= "ON DUPLICATE KEY UPDATE name =  VALUES(name),avatar = VALUES(avatar),type =  VALUES(type),gender =  VALUES(gender),position =  VALUES(position),corp_name =  VALUES(corp_name),corp_full_name =  VALUES(corp_full_name),external_profile =  VALUES(external_profile),remark =  VALUES(remark),description =  VALUES(description),tags =  VALUES(tags),remark_corp_name =  VALUES(remark_corp_name),remark_mobiles =  VALUES(remark_mobiles)";
		$resu = db_query($sql);
		return $res;
	}
	
	public function ceshi3(){
		set_time_limit(0);
		setApi();
		$wid = 46;
		$qyConfig = (new Model('qy_wechat_config'))->find(['wid'=>$wid]);
		$QyWechatApi = QyWechatApi::getInstance();
		if(!file_exists('ass.txt')){
		   file_put_contents('ass.txt',0);
		}
		$id = file_get_contents('ass.txt');
		$data = (new Model('qy_user_list'))->field('id,userid')->where(['id@>'=>$id,'wid'=>$wid,'is_del@!='=>1])->order('id asc')->limit(100)->list_all_array();
		if(count($data) == 0){
		   file_put_contents('ass.txt',0);
		}
		file_put_contents('ass.txt',$data[count($data)-1]['id']);
		$res = json_encode([
        	'code' => 'success',
        	'msg'=>$id
        ]);
		$customer_list_arr = [];
		foreach($data as $user){
		    $datas = [];
		    $sql = "INSERT INTO qvmh_qy_externalcontact_list ( wid, external_userid, name,avatar,type,gender,unionid,position,corp_name,corp_full_name,external_profile,user_id,remark,description,createtime,tags_info,tags,remark_corp_name,remark_mobiles,add_way,oper_userid,state) VALUES";
			$user_id = $user['id'];
			$customer_list_res = $QyWechatApi->get_et_list($user['userid'],$wid);
			if(count($customer_list_res)){
				foreach ($customer_list_res as $customer_list => $customer_info) {
					$tags = [];
					$users = $customer_info['follow_info'];
					$tags = $customer_info['follow_info']['tag_id'];
					$wid = $wid;
					$external_userid = $customer_info['external_contact']['external_userid'];
					$name = Helper::getInstance()->filterEmoji($customer_info['external_contact']['name'])??null;
				    // $name = $customer_info['external_contact']['name'];
					$avatar = $customer_info['external_contact']['avatar']??null;
					$type = $customer_info['external_contact']['type']??null;
					$gender = $customer_info['external_contact']['gender']??null;
					$unionid = $customer_info['external_contact']['unionid']??null;
					$position = $customer_info['external_contact']['position']??null;
					$corp_name = $customer_info['external_contact']['corp_name']??null;
					$corp_full_name = $customer_info['external_contact']['corp_full_name']??null;
					$external_profile = json_encode($customer_info['external_contact']['external_profile'],320);
				    $external_profile = null;
					$remark = Helper::getInstance()->filterEmoji($users['remark'])??null;
					$description = $users['description']??null;
					$createtime = $users['createtime']??null;
					$tags_info = json_encode($users['tag_id'],320);
					$tags = json_encode($tags,320);
					$remark_corp_name = $users['remark_corp_name']??null;
					$remark_mobiles = json_encode($users['remark_mobiles'],320);
					$add_way = $users['add_way']?:0;
					$oper_userid = $users['oper_userid']??null;
					$state = $users['state']??null;
					$datas[] = "($wid,'{$external_userid}','{$name}','{$avatar}',{$type},{$gender},'{$unionid}','{$position}','{$corp_name}','{$corp_full_name}','{$external_profile}',{$user_id},'{$remark}','{$description}','{$createtime}','{$tags_info}','{$tags}','{$remark_corp_name}','{$remark_mobiles}',{$add_way},'{$oper_userid}','{$state}')";
				}
			}else{
			    continue;
			}
    		$sql .= implode(',', $datas);
    		$sql .= "ON DUPLICATE KEY UPDATE name =  VALUES(name),avatar = VALUES(avatar),type =  VALUES(type),gender =  VALUES(gender),position =  VALUES(position),corp_name =  VALUES(corp_name),corp_full_name =  VALUES(corp_full_name),external_profile =  VALUES(external_profile),remark =  VALUES(remark),description =  VALUES(description),tags =  VALUES(tags),remark_corp_name =  VALUES(remark_corp_name),remark_mobiles =  VALUES(remark_mobiles)";
    		$resu = db_query($sql);
		}
		return $res;
	}
	
	public function tongbu_customer(){
		set_time_limit(0);
		setApi();
		$wid = Session::get('wid');
		$qyConfig = (new Model('qy_wechat_config'))->find(['wid'=>$wid]);
		$QyWechatApi = QyWechatApi::getInstance();
		$etApp = $QyWechatApi->get_qy_app($qyConfig->corp_id,$qyConfig->externalcontact_secret);
		//获取通讯录列表
		$qyUser = (new Model('qy_user_list'))->where(['wid'=>$wid,'status@!='=>5,'is_del@!='=>1])->list_all();
		$customer_list_arr = [];
		foreach($qyUser as $qyuser){
			//获取客户列表
			$customer_list_res = $etApp->external_contact->list($qyuser->userid);
			if($customer_list_res['errcode'] == 0  && count($customer_list_res['external_userid'])){
				$customer_list_arr[$qyuser->id] = $customer_list_res['external_userid'];
			}
		}
		//导数据
		foreach($customer_list_arr as $user_id => $customer_list){
			foreach($customer_list as $customer){
				//获取客户详情
				$customer_info_res = $etApp->external_contact->get($customer);
				if($customer_info_res['errcode'] == 0){
					$customer_info = $customer_info_res;
					$qyCustomer = (new Model('qy_externalcontact_list'))->find(['wid'=>$wid,'user_id'=>$user_id,'external_userid'=>$customer_info['external_contact']['external_userid']]);
					$qyUserById = (new Model('qy_user_list'))->find(['id'=>$user_id]);

					$user = '';
					$tags = [];
					foreach($customer_info['follow_user'] as $followuser){
						if($qyUserById->userid == $followuser['userid']){
							$user = $followuser;
							foreach($followuser['tags'] as $ftag){
								$tags[] = $ftag['tag_id'];
							}
						}
					}						
					$qyCustomer->wid = $wid;
					$qyCustomer->external_userid = $customer_info['external_contact']['external_userid'];
					$qyCustomer->name = Helper::getInstance()->filterEmoji($customer_info['external_contact']['name']);
					$qyCustomer->avatar = $customer_info['external_contact']['avatar'];
					$qyCustomer->type = $customer_info['external_contact']['type'];
					$qyCustomer->gender = $customer_info['external_contact']['gender'];
					$qyCustomer->unionid = $customer_info['external_contact']['unionid'];
					$qyCustomer->position = $customer_info['external_contact']['position'];
					$qyCustomer->corp_name = $customer_info['external_contact']['corp_name'];
					$qyCustomer->corp_full_name = $customer_info['external_contact']['corp_full_name'];
					$qyCustomer->external_profile = json_encode($customer_info['external_contact']['external_profile']);
					$qyCustomer->user_id = $user_id;
					$qyCustomer->remark = Helper::getInstance()->filterEmoji($user['remark']);
					$qyCustomer->description = $user['description'];
					$qyCustomer->createtime = $user['createtime'];
					$qyCustomer->tags_info = json_encode($user['tags']);
					$qyCustomer->tags = json_encode($tags);
					$qyCustomer->remark_corp_name = $user['remark_corp_name'];
					$qyCustomer->remark_mobiles = $user['remark_mobiles'];
					$qyCustomer->add_way = $user['add_way'];
					$qyCustomer->oper_userid = $user['oper_userid'];
					$qyCustomer->state = $user['state'];
					$qyCustomer->status = 0;
					$qyCustomer->save();
										
				}
			}
		}
		sendSuccess('已同步'); 
	}
	
	public function groupchat_manage(){
		return $this->show();
	}
	 
	public function groupchat_list(){
		$wid = Session::get('wid');
		$etGroupchat = new Model('qy_et_groupchat');
		//name 模糊查询
		$name = \Request::get("name");
		if(trim($name)!=''){
			$where['name@~'] = $name;	
		}
		$h = Helper::getInstance(); 
		$r_user_id_arr = $h->get_check_range('et_data');
		if($r_user_id_arr){
			$where['user_id'] = $r_user_id_arr;
		}
		$where['wid'] = $wid;
		$where['user_id@!='] = "";
		$r_type = Session::get('r_type');
		$daat = (new Model('qy_et_groupchat'))->where($where)->list_all();
		foreach($daat as $key=>$value){
			$user = (new Model('qy_user_list'))->find(['wid'=>$wid,'id'=>$value->user_id]);
			if($user->is_del == 1){
				unset($daat[$key]);
			}else{
				$ids[] = $value->id;
			}
		}
		$p = new \Pagination();		
		$res = $p->model_list($etGroupchat->where(['id'=>$ids])->order('id'));
		foreach($res as $k=>$v){
			$user = (new Model('qy_user_list'))->find(['wid'=>$wid,'id'=>$v->user_id]);
			$res[$k]->user = $user;
			$res[$k]->member_list = json_decode($v->member_list,1);
			$res[$k]->tags = json_decode($v->tags,1);
		}
		$chatTagArr = $this->getChatTags();

		//点大
		$sc_point_config = (new Model('sc_point_confing'))->find();
		$pb_exist = false;
		if($sc_point_config->id && $sc_point_config->database_ip && $sc_point_config->user_name){
			$pb_exist = true;
		}

		$this->assign('pb_exist', $pb_exist);
		$this->assign('tj', $tj);
		$this->assign("p", $p);
		$this->assign("P", $GLOBALS['P']);
		$this->assign("res", $res);
		$this->assign("chatTagArr", $chatTagArr);
		return $this->show();
	}
	/**
	* 设置点大等级
	*/
	public function point_setlevel(){
		$wid = Session::get('wid');
		$id = \Request::get(1);
		if(!$id) die("网络错误,请刷新重试");
		$setlevel = (new Model('sc_point_setlevel'))->find(['wid'=>$wid,'type'=>1,'chat_id'=>$id]);
		if(is_post()){
			setApi();
			if(!$setlevel->id){
				$setlevel->wid = $wid;
				$setlevel->type = 1;
				$setlevel->chat_id = $id;
				$setlevel->ctime = time();
			}
			$setlevel->level_id = $_POST['levelId'];
			$status = $_POST['status'] ? 1:0;
			$setlevel->status =  $status;

			if($status){
				if(!$_POST['endtime']) sendError("请填写有效期");
				$setlevel->endtime =  strtotime($_POST['endtime']);
			}
			
			if($setlevel->save()) sendSuccess('设置成功');
			sendError('设置失败');
		}
		//点大
		$sc_point_set = (new Model('sc_point_set'))->find(['wid'=>$wid]);
		$pbLevels = [];
		if($sc_point_set->id && $sc_point_set->da_id){
			$pbLevels = (new SyncPointBigData())->selectLevel($sc_point_set->da_id);
		}else{
			die("请先配置点大商城账户");
		}
		$this->assign("pbLevels", $pbLevels);
		$this->assign("pb_exist", $pb_exist);
		$this->assign("setlevel", $setlevel);
		return $this->show();
	}
	public function groupchat_make_tag(){
		$wid = Session::get('wid');
		$id = \Request::get(1);
		$chatTags = (new Model('qy_et_groupchat_tag'))->where(['wid'=>$wid])->list_all_array();
		$groupchat = (new Model('qy_et_groupchat'))->find($id);
		$nowChatTag = json_decode($groupchat->tags,1);
		if(is_post()){
			setApi();
			$tags = $_POST['tags'] ?? [];
			$groupchat->tags = json_encode($tags,320);
			if($groupchat->save()){
				sendSuccess('操作成功');
			}
			sendError('操作失败');
		}
		$this->assign("chatTags", $chatTags);
		$this->assign("nowChatTag", $nowChatTag);
		return $this->show();
	}

	//获取群标签数组
	public function getChatTags(){
		$wid = Session::get('wid');
		$chatTags = (new Model('qy_et_groupchat_tag'))->where(['wid'=>$wid])->list_all();
		$res = [];
		foreach ($chatTags as $tag) {
			$tag = json_decode($tag->tags,1);
			foreach ($tag as $val) {
				$res[$val['id']] = $val['name'];
			}
		}
		return $res;
	}
	public function groupchat_info(){
		setApi();
		$wid = Session::get('wid');
		$chatid = $_POST['chatid'];
		foreach ($chatid as $key => $value) {
			$etGroupchat[] = (new Model('qy_et_groupchat'))->find(['wid'=>$wid,'chat_id'=>$value]);
		}
		foreach ($etGroupchat as $keys => $values) {
			if($values->name == ""){
				$values->name = "默认群名";
			}
		}
		sendSuccess('获取成功',$etGroupchat);
	}
	
	public function user_creat_groupchat_statistic(){
		if(\Request::get('dates')){
			$dates = \Request::get('dates');
		}else{
			$dates = date('Y-m-d',strtotime("-1 day"));//昨天
		}
		$wid = Session::get('wid');
		$qyUser = new Model('qy_user_list');
		$where['wid'] = $wid;
		$where['is_del'] = 0;
		$r_type = Session::get('r_type');
		$h = Helper::getInstance(); 
		$r_user_id_arr = $h->get_check_range('et_data');
		if($r_user_id_arr){
			$where['id'] = $r_user_id_arr; 
		}
		$p = new \Pagination();
		$res = $p->model_list($qyUser->where($where)->order('id'));
		//获取客户群统计数据
		$QyWechatApi = QyWechatApi::getInstance();
		$etGroupchatStatistic = $QyWechatApi->get_et_groupchat_statistic(strtotime($dates))['items'];
		foreach($res as $k=>$v){
			foreach($etGroupchatStatistic as $statistic){
				if($v->userid == $statistic['owner']){
					$res[$k]->groupchatStatistic = $statistic['data'];
					break;
				}
			}
		}
		$this->assign("p", $p);
		$this->assign("P", $GLOBALS['P']);
		$this->assign("res", $res);
		$this->assign("dates", $dates);
		return $this->show();
	}
	
		public function select_details(){
			$wid = Session::get('wid');
			$id = \Request::get(1);
			$groupchat = (new Model('qy_et_groupchat'))->find($id)->get_model_array();
			$member_list = json_decode($groupchat['member_list']);//取出入群列表
			foreach ($member_list as $list_key => $list_value) {
				if(!$list_value->invitor){
					unset($member_list[$list_key]);
					continue;
				}else{
					$datas[] = $list_value->invitor->userid;    //查出所有的邀请人
				}
				if($list_value->type == 1){
					$user = (new Model("qy_user_list"))->field("name,avatar")->find(["wid"=>$wid,"userid"=>$list_value->userid])->get_model_array();
				}else{
					$user = (new Model("qy_externalcontact_list"))->field("name,avatar")->find(["wid"=>$wid,"external_userid"=>$list_value->userid])->get_model_array();
					if(!$user["name"]){
					    $user["name"] = "外部联系人";
					    $user["avatar"] = "http://weidogstest.oss-cn-beijing.aliyuncs.com/e269ef3829d007bb43096233e6da5145.png";
					}
				}
				$member_list[$list_key]->join_time = date("Y-m-d H:i:s",$list_value->join_time);
				$member_list[$list_key]->user = $user;
			}
			$datas = array_unique($datas); //去重邀请人
			foreach ($datas as $key => $value) {
				$data = (new Model("qy_user_list"))->field("name,avatar,userid")->find(["wid"=>$wid,"userid"=>$value])->get_model_array();
				$data_list[] = $data;
				//循环邀请人获取信息
			}
			if(count($data_list) < 1){
				echo '暂无邀请数据';die;
			}
			$this->assign("member_list", $member_list);
			$this->assign("data_list", $data_list);
			return $this->show();
		}
	/**public function tongbu_groupchat(){
		set_time_limit(0);
		setApi();
		$wid = Session::get('wid');
		$qyConfig = (new Model('qy_wechat_config'))->find(['wid'=>$wid]);
		$QyWechatApi = QyWechatApi::getInstance();
		//获取群列表
		$groupChatList = [];
		$groupchatListRes = $QyWechatApi->get_et_groupchat_list();
		if($groupchatListRes['errcode'] == 0){
			$groupChatList = $groupchatListRes['group_chat_list'];
		}
		(new Model('qy_et_groupchat'))->delete(['wid'=>$wid]);
		foreach($groupChatList as $groupChat){
			$status = $groupChat['status'];
			//获取群详情
			$groupChatInfoRes = $QyWechatApi->get_et_groupchat_info($groupChat['chat_id']);
			if($groupChatInfoRes['errcode'] == 0){
				$groupChatInfo = $groupChatInfoRes['group_chat'];
				$etGroupchat = new Model('qy_et_groupchat');
				$etGroupchat->wid = $wid;
				$etGroupchat->chat_id = $groupChatInfo['chat_id'];
				$etGroupchat->status = $status;
				$etGroupchat->name = $groupChatInfo['name'];
				$etGroupchat->owner = $groupChatInfo['owner'];
				$etGroupchat->create_time = $groupChatInfo['create_time'];
				$etGroupchat->notice = Helper::getInstance()->filterEmoji($groupChatInfo['notice']);
				$etGroupchat->member_list = json_encode($groupChatInfo['member_list'],320);
				$etGroupchat->save();
			}
		}
		sendSuccess('已同步');
	}*/

	public function tongbu_groupchat(){
		set_time_limit(0);
		setApi();
		$wid = Session::get('wid');
		$qyConfig = (new Model('qy_wechat_config'))->find(['wid'=>$wid]);
		$QyWechatApi = QyWechatApi::getInstance();
		$groupChatList = $QyWechatApi->get_et_groupchat_list();
		$data_list = array_chunk($groupChatList, 10);
		$h = Helper::getInstance();
		foreach($data_list as $key=>$groupChat){
		    $data = http_build_query($groupChat);
		    $ch = curl_init();
            curl_setopt($ch, CURLOPT_URL, $h->get_http_server_name()."/Addons/QyWechat/Admin/Externalcontact/tongbu_groupchats-".$wid.".html");
		    curl_setopt($ch, CURLOPT_POSTFIELDS, $data); //post 传参
            $output = curl_exec($ch);
            curl_close($ch);
		}
		sendSuccess('已同步');
	}
	
	public function tongbu_groupchats(){
	    $wid = \Request::get(1);
	    $data = $_POST;
	    $chatid_arr = array();
		$QyWechatApi = QyWechatApi::getInstance();
	    foreach($data as $groupChat){
	        $status = $groupChat['status'];
	        $groupChatInfoRes = $QyWechatApi->get_et_groupchat_info($groupChat['chat_id'],$wid);
	        if($groupChatInfoRes['errcode'] == 0){
	            $groupChatInfo = $groupChatInfoRes['group_chat'];
				$qyUser = (new Model('qy_user_list'))->field("id")->find(['wid'=>$wid,'userid'=>$groupChatInfo['owner']]);
				$etGroupchat = (new Model('qy_et_groupchat'))->find(['wid'=>$wid,'chat_id'=>$groupChatInfo['chat_id']]);
				$etGroupchat->wid = $wid;
				$etGroupchat->chat_id = $groupChatInfo['chat_id'];
				$etGroupchat->status = $status;
				$etGroupchat->name = Helper::getInstance()->filterEmoji($groupChatInfo['name']);
				$etGroupchat->user_id = $qyUser->id;
				$etGroupchat->create_time = $groupChatInfo['create_time'];
				$etGroupchat->notice = Helper::getInstance()->filterEmoji($groupChatInfo['notice']);
				$etGroupchat->member_list = json_encode($groupChatInfo['member_list']);
				$etGroupchat->save();
	        }else{
	            $chatid_arr[] = $groupChat['chat_id'];
	        }
	    }
	    $groupChatListDel = (new Model('qy_et_groupchat'))->where(['wid'=>$wid])->list_all();
		foreach ($groupChatListDel as $k => $del) {
			if(in_array($del->chat_id, $chatid_arr)){
				$groupChatListDel[$k]->remove();
			}
		}
	}
	
	public function auto_pull_group(){
		$wid = Session::get('wid');
		$contactWay = new Model('qy_et_contact_way');
		//name 模糊查询
		$name = $_GET['name'];
		if(trim($name)!=''){
			$where['name@~'] = $name;	
		}
		$where['wid'] = $wid;
		$where['is_auto_pull_group'] = 1;
		$p = new \Pagination();		
		$res = $p->model_list($contactWay->where($where)->order('id desc'));
		foreach($res as $k=>$v){
			$res[$k]->users = json_decode($v->users,1);
			$res[$k]->select_label = json_decode($v->select_label,1);
			$group_chat_list = json_decode($v->group_chat_list,1);
			$isHaveLr = 0;
			$customTotalNum = 0;
			foreach($group_chat_list as $k2=>$group_chat){
				$etGroupchat = (new Model('qy_et_groupchat'))->find(['wid'=>$wid,'chat_id'=>$group_chat['chatid']]);
				$customNum = count(json_decode($etGroupchat->member_list,1));
				$customTotalNum += $customNum;
				$group_chat_list[$k2]['name'] = $group_chat['name']."({$customNum}/200)";
				if($customNum < $group_chat['people'] && $isHaveLr == 0){
					$isHaveLr = 1;
					$group_chat_list[$k2]['status'] = 1;//0未开始 1拉人中 2已结束
				}elseif($customNum < $group_chat['people']){
					$group_chat_list[$k2]['status'] = 0;
				}elseif($customNum >= $group_chat['people']){
					$group_chat_list[$k2]['status'] = 2;
				}
			}
			$res[$k]->customTotalNum = $customTotalNum;
			$res[$k]->group_chat_list = $group_chat_list;
		}
		$this->assign("p", $p);
		$this->assign("P", $GLOBALS['P']);
		$this->assign("res", $res);
		$this->assign("name", $name);
		$this->assign("h", Helper::getInstance());
		return $this->show();
	}
	
	public function add_auto_pull_group(){
		$wid = Session::get('wid');
		$QyWechatApi = QyWechatApi::getInstance();
		$qyConfig = (new Model('qy_wechat_config'))->find(['wid'=>$wid]);
		$etApp = $QyWechatApi->get_qy_app($qyConfig->corp_id,$qyConfig->externalcontact_secret);
		$contactWay = new Model('qy_et_contact_way');
		$id = \Request::get(1);
		if($id){
			$contactWay->find(['wid'=>$wid,'id'=>$id]);
		}
		if(is_post()){
			setApi();
			if(!$_POST['checkUser']){
				sendError('请添加使用人员');
			}
			if($_POST['auto_label'] && !$_POST['checkLable']){
				sendError('请添加标签');
			}
			$type = 2;
			$scene = 2;//2-通过二维码联系
			$users = explode(',',$_POST['checkUser']);
			if($contactWay->id){
				$configId = $contactWay->config_id;
				$state = $contactWay->state;
				$config = [
				   'skip_verify' => $_POST['skip_verify']?true:false,
				   'user' => Helper::get_userid($users)
				];
				$updateRes = $etApp->contact_way->update($configId, $config);
				if($updateRes['errcode'] == 0){
					$contactWay->wid = $wid;
				}else{
					if($updateRes['errcode'] == 84074){
						sendError('此成员没有外部联系人权限');
					}
					sendError('操作失败');
				}
			}else{
				$maxId = (new Model('qy_et_contact_way'))->max('id');
				$state = $maxId + 1;//企业自定义的state参数，用于区分不同的添加渠道
				$config = [
				   'skip_verify' => $_POST['skip_verify']?true:false,//外部客户添加时是否无需验证
				   'state' => $state,
				   'user' => Helper::get_userid($users),
				];
				$createRes = $etApp->contact_way->create($type, $scene, $config);
				if($createRes['errcode'] == 0){
					$config_id = $createRes['config_id'];
					$getContactWay = $etApp->contact_way->get($config_id)['contact_way'];
					$contactWay->wid = $wid;
					$contactWay->config_id = $config_id;
					$contactWay->qr_code = $getContactWay['qr_code'];
					$contactWay->ctime = date('Y-m-d H:i:s');
				}else{
					if($createRes['errcode'] == 84074){
						sendError('此成员没有外部联系人权限');
					}
					sendError('操作失败');
				}
			}
			$itemId = $_POST['item_id'];
			$itemChatid = $_POST['item_chatid'];
			$itemName = $_POST['item_name'];
			$itemPeople = $_POST['item_people'];
			$itemImg = $_POST['item_img'];
			$itmeArr = [];
			foreach($itemId as $k=>$id){
				$itmeArr[$k]['id'] = $id;
				$itmeArr[$k]['chatid'] = $itemChatid[$k];
				$itmeArr[$k]['name'] = $itemName[$k];
				$itmeArr[$k]['people'] = $itemPeople[$k];
				$itmeArr[$k]['img'] = $itemImg[$k];
			}
			$contactWay->group_chat_list = json_encode($itmeArr,320);
			$contactWay->name = $_POST['name'];
			$contactWay->skip_verify = $_POST['skip_verify'];
			$contactWay->state = $state;
			$contactWay->users = json_encode($users,320);
			$contactWay->type = $type;
			$contactWay->auto_label = $_POST['auto_label']?1:0;
			$contactWay->select_label = json_encode(explode(',',$_POST['checkLable']),320);
			$contactWay->text_content = $_POST['text_content'];
			$contactWay->other_type = 2;
			$contactWay->is_auto_pull_group = 1;
			$contactWay->save();
			sendSuccess('操作成功');
		}
		$this->assign("contactWay", $contactWay);
		$this->assign("group_chat_list", json_decode($contactWay->group_chat_list,1));
		$this->assign("h", Helper::getInstance());
		return $this->show();
	}
	
	public function del_auto_pull_group(){
		setApi();
		$wid = Session::get('wid');
		$QyWechatApi = QyWechatApi::getInstance();
		$qyConfig = (new Model('qy_wechat_config'))->find(['wid'=>$wid]);
		$etApp = $QyWechatApi->get_qy_app($qyConfig->corp_id,$qyConfig->externalcontact_secret);
		$id = $_POST['id'];
		if($id){
			$contactWay = (new Model('qy_et_contact_way'))->find($id);
		}else{
			sendError('参数错误');
		}
		$configId = $contactWay->config_id;
		$deleteRes = $etApp->contact_way->delete($configId);
		if($deleteRes['errcode'] == 0){
			$contactWay->delete();
			sendSuccess('操作成功');
		}else{
			sendError('操作失败');
		}
		
	}
	
	public function group_welcome_template(){
		$wid = Session::get('wid');
		$groupWelcome = new Model('qy_group_welcome_template');
		//text_content 模糊查询
		$text_content = $_GET['text_content'];
		if(trim($text_content)!=''){
			$where['text_content@~'] = $text_content;	
		}
		$where['wid'] = $wid;
		$p = new \Pagination();		
		$res = $p->model_list($groupWelcome->where($where)->order('id desc'));
		foreach($res as $k=>$v){
			if($v->other_type == 1){
				$sendType = '文本';
			}elseif($v->other_type == 2){
				$sendType = '图片';
			}elseif($v->other_type == 3){
				$sendType = '图文';
			}elseif($v->other_type == 4){
				$sendType = '小程序';
			}
			$res[$k]->sendType = $sendType;
		}
		$this->assign("p", $p);
		$this->assign("P", $GLOBALS['P']);
		$this->assign("res", $res);
		$this->assign("name", $name);
		return $this->show();
	}
	
	public function add_group_welcome(){
		$wid = Session::get('wid');
		$QyWechatApi = QyWechatApi::getInstance();
		$qyConfig = (new Model('qy_wechat_config'))->find(['wid'=>$wid]);
		$etApp = $QyWechatApi->get_qy_app($qyConfig->corp_id,$qyConfig->externalcontact_secret);
		$groupWelcome = new Model('qy_group_welcome_template');
		if(\Request::get(1)){
			$groupWelcome->find(\Request::get(1));
		}
		if(is_post()){
			setApi();
			$msg = [
				'text'=>[
					'content' => $_POST['text_content']
				]
			];
			if(strpos($_POST['image'],$_SERVER['HTTP_HOST'])){
			    $_POST['image'] = str_replace("https://".$_SERVER['HTTP_HOST'],".",$_POST['image']);
			}
			if($_POST['shareType'] == 2){
				$msg['image'] = [
					'media_id' => $etApp->media->uploadImage($_POST['image'])['media_id'],
				];
			}elseif($_POST['shareType'] == 3){
				$msg['link'] = [
					'title' => $_POST['link_title'],
					'picurl' => $_POST['link_pic'],
					'desc' => $_POST['link_desc'],
					'url' => $_POST['link_url'],
				];
			}elseif($_POST['shareType'] == 4){
				$msg['miniprogram'] = [
					'title' => $_POST['miniprogram_title'],
					'pic_media_id' => $etApp->media->uploadImage($_POST['miniprogram_pic'])['media_id'],
					'appid' => $_POST['miniprogram_appid'],
					'page' => $_POST['miniprogram_page'],
				 ];
			}
			if($groupWelcome->id){
				$msg['template_id'] = $groupWelcome->template_id;
				$editRes = $QyWechatApi->edit_group_welcome_template($msg);
				if($editRes['errcode'] == 0){
					$groupWelcome->wid = $wid;
				}else{
					sendError('操作失败'.$editRes['errmsg']);
				}
			}else{
				$addRes = $QyWechatApi->add_group_welcome_template($msg);
				if($addRes['errcode'] == 0){
					$groupWelcome->wid = $wid;
					$groupWelcome->template_id = $addRes['template_id'];
					$groupWelcome->ctime = date('Y-m-d H:i:s');
				}else{
					sendError('操作失败'.$addRes['errmsg']);
				}
			}
			$groupWelcome->text_content = $_POST['text_content'];
			$groupWelcome->other_type = $_POST['shareType'];
			$groupWelcome->image_url = $_POST['image'];
			$groupWelcome->link_title = $_POST['link_title'];
			$groupWelcome->link_picurl = $_POST['link_pic'];
			$groupWelcome->link_desc = $_POST['link_desc'];
			$groupWelcome->link_url = $_POST['link_url'];
			$groupWelcome->miniprogram_name = $_POST['miniprogram_name'];
			$groupWelcome->miniprogram_title = $_POST['miniprogram_title'];
			$groupWelcome->miniprogram_url = $_POST['miniprogram_pic'];
			$groupWelcome->miniprogram_appid = $_POST['miniprogram_appid'];
			$groupWelcome->miniprogram_page = $_POST['miniprogram_page'];
			$groupWelcome->save();
			sendSuccess('操作成功');
		}
		$this->assign("groupWelcome", $groupWelcome);
		return $this->show();
	}
	
	public function del_group_welcome(){
		setApi();
		$wid = Session::get('wid');
		$QyWechatApi = QyWechatApi::getInstance();
		$id = $_POST['id'];
		if($id){
			$groupWelcome = (new Model('qy_group_welcome_template'))->find($id);
		}else{
			sendError('参数错误');
		}
		$delRes = $QyWechatApi->del_group_welcome_template($groupWelcome->template_id);
		if($delRes['errcode'] == 0 || $delRes['errcode'] == 40037){
			$groupWelcome->delete();
			sendSuccess('操作成功');
		}else{
			sendError('操作失败:'.$delRes['errmsg']);
		}
	}
	
	public function msg_template(){
		$wid = Session::get('wid');
		$msgTemplate = new Model('qy_et_msg_template');
		//name 模糊查询
		$name = $_GET['name'];
		if(trim($name)!=''){
			$where['name@~'] = $name;
		}
		$where['wid'] = $wid;
		$p = new \Pagination();		
		$res = $p->model_list($msgTemplate->where($where)->order('id desc'));
		foreach($res as $k=>$v){
			if($v->other_type == 1){
				$sendType = '文本';
			}elseif($v->other_type == 2){
				$sendType = '图片';
			}elseif($v->other_type == 3){
				$sendType = '图文';
			}elseif($v->other_type == 4){
				$sendType = '小程序';
			}
			$res[$k]->sendType = $sendType;
		}
		$this->assign("p", $p);
		$this->assign("P", $GLOBALS['P']);
		$this->assign("res", $res);
		$this->assign("name", $name);
		return $this->show();
	}
	public function add_msg_templates(){
	    setApi(); 
		$wid = Session::get('wid');
		$QyWechatApi = QyWechatApi::getInstance();
		$qyConfig = (new Model('qy_wechat_config'))->find(['wid'=>$wid]);
		$etApp = $QyWechatApi->get_qy_app($qyConfig->corp_id,$qyConfig->externalcontact_secret);
		$msgTemplate = (new Model('qy_et_msg_template'))->find($_POST["id"]);
		if($msgTemplate->send_mode == 1){
			$external_userids = [];
			$msg = [];
			$msg['text'] = ['content'=>json_decode($msgTemplate->text_content)];
			if($msgTemplate->other_type == 2){//图片
				$image_url_arr = parse_url($msgTemplate->image_url);
				if($image_url_arr['host'] == $_SERVER["HTTP_HOST"]){
					$msg['image'] = ['media_id'=>$etApp->media->uploadImage('.'.$image_url_arr['path'])['media_id']];
				}else{
					$msg['image'] = ['media_id'=>$etApp->media->uploadImage($msgTemplate->image_url)['media_id']];
				}
			}elseif($msgTemplate->other_type == 3){//图文
				$msg['link'] = [
					'title'=>$msgTemplate->link_title,
					'picurl'=>$msgTemplate->link_picurl,
					'desc'=>$msgTemplate->link_desc,
					'url'=>$msgTemplate->link_url
				];
			}elseif($msgTemplate->other_type == 4){//小程序
				$image_url_arr = parse_url($msgTemplate->miniprogram_picurl);
				if($image_url_arr['host'] == $_SERVER["HTTP_HOST"]){
					$media_id = $etApp->media->uploadImage('.'.$image_url_arr['path'])['media_id'];
				}else{
					$media_id = $etApp->media->uploadImage($msgTemplate->miniprogram_picurl)['media_id'];
				}
				$msg['miniprogram'] = [
					'title'=>$msgTemplate->miniprogram_title,
					'pic_media_id'=>$media_id,
					'appid'=>$msgTemplate->miniprogram_appid,
					'page'=>$msgTemplate->miniprogram_page
				];
			}

			$res = false;
			if($msgTemplate->send_to == 1){
				$page = $_POST["page"]*5000;
				$externalcontact = array_column((new Model('qy_externalcontact_list'))->field('external_userid')->where(['wid'=>$wid,"status"=>0])->limit($page,5000)->list_all_array(),"external_userid");
    		    $msg['external_userid'] = array_merge(array_unique($externalcontact));
    		    if(!count($externalcontact)){
    		    	$res = true;
    		    }else{
    		    	$messageRes = $etApp->external_contact_message->submit($msg);
    		    	if($messageRes['errcode'] == 0){
    		    	    $newMsgid = $msgTemplate->msgid?explode(",", $msgTemplate->msgid):[];
    		    	    array_push($newMsgid,$messageRes['msgid']);
    		    	    $msgTemplate->msgid = implode(",", $newMsgid);
						$msgTemplate->status = 1;
    		    	    $msgTemplate->save();
    		    	}
    		    	sendSuccess($messageRes["errmsg"],1);
    		    }
			}elseif($msgTemplate->send_to == 2){
				$page = $_POST["page"]*5000;
				$sql = "select external_userid from qvmh_qy_externalcontact_list where wid={$wid} and status=0 and (";
				foreach(json_decode($msgTemplate->send_tag,1) as $tag){
					$sql .= "tags like '%\"{$tag}\"%' or ";
				}
				$sql = chop($sql,"or ");
				$sql .= ")";
				$sql .= " ORDER BY id DESC limit {$page},5000";
				//array_merge 排序
				//array_unique 去重
				//array_column 取出列
				$external_userids = array_merge(array_unique(array_column(db_query($sql),"external_userid")));
    		    $msg['external_userid'] = $external_userids;
				if(!count($external_userids)){
					$res = true;
				}else{
    		    	$messageRes = $etApp->external_contact_message->submit($msg);
    		    	if($messageRes['errcode'] == 0){
    		    	    $newMsgid = $msgTemplate->msgid?explode(",", $msgTemplate->msgid):[];
    		    	    array_push($newMsgid,$messageRes['msgid']);
    		    	    $msgTemplate->msgid = implode(",", $newMsgid);
						$msgTemplate->status = 1;
    		    	    $msgTemplate->save();
    		    	}
    		    	sendSuccess($messageRes["errmsg"],1);
				}
			}elseif($msgTemplate->send_to == 3){
				foreach(json_decode($msgTemplate->send_user,1) as $user_id){
					$external_userids = array_column((new Model('qy_externalcontact_list'))->field('external_userid')->where(['wid'=>$wid,'user_id'=>$user_id])->list_all_array(), 'external_userid');
					$msg['external_userid'] = $external_userids;
					$user = Helper::getInstance()->get_user_by_id($wid,$user_id);
					$msg['sender'] = $user['userid'];
					$messageRes = $etApp->external_contact_message->submit($msg);
					if($messageRes['errcode'] == 0){
						$res = true;
						$msgidList[] = $messageRes['msgid'];
					}
				}
				$msgTemplate->status = 1;
	    	    $msgTemplate->msgid = implode(",", $msgidList);
	    	    $msgTemplate->save();
			}
			sendError("操作成功");
		}
	}
	
	public function add_msg_template(){
		$wid = Session::get('wid');
		$QyWechatApi = QyWechatApi::getInstance();
		$qyConfig = (new Model('qy_wechat_config'))->find(['wid'=>$wid]);
		$etApp = $QyWechatApi->get_qy_app($qyConfig->corp_id,$qyConfig->externalcontact_secret);
		if(is_post()){
			setApi();
			if($_POST['shareuser']==3 && !$_POST['checkUser']){
				sendError("请选择员工");
			}else if($_POST['shareuser']==2 && !$_POST['checkLable']){
				sendError("请选择标签");
			}
			$txt = json_encode($_POST['text_content']); 
			$msgTemplate = new Model('qy_et_msg_template');
			$msgTemplate->wid = $wid;
			$msgTemplate->name = $_POST['name'];
			$msgTemplate->send_to = $_POST['shareuser'];
			$msgTemplate->send_tag = json_encode(explode(',',$_POST['checkLable']),320);
			$msgTemplate->send_user = json_encode(explode(',',$_POST['checkUser']),320);
			$msgTemplate->send_mode = $_POST['selectTime'];
			$msgTemplate->timing_time = $_POST['timing_time'];
			$msgTemplate->text_content = $txt;
			$msgTemplate->other_type = $_POST['shareType'];
			$msgTemplate->image_url = $_POST['image'];			
			$msgTemplate->link_title = $_POST['link_title'];
			$msgTemplate->link_picurl = $_POST['link_pic'];
			$msgTemplate->link_desc = $_POST['link_desc'];
			$msgTemplate->link_url = $_POST['link_url'];
			$msgTemplate->miniprogram_name = $_POST['miniprogram_name'];
			$msgTemplate->miniprogram_appid = $_POST['miniprogram_appid'];
			$msgTemplate->miniprogram_page = $_POST['miniprogram_page'];
			$msgTemplate->miniprogram_title = $_POST['miniprogram_title'];
			$msgTemplate->miniprogram_picurl = $_POST['miniprogram_pic'];
			$msgTemplate->ctime = date('Y-m-d H:i:s');
			if($msgTemplate->save()){
				// if($msgTemplate->send_mode == 1){
				// 	$externalcontact = (new Model('qy_externalcontact_list'))->field('external_userid,tags')->where(['wid'=>$wid])->list_all_array();
				// 	$external_userids = [];
				// 	$msg = [];
				// 	$msg['text'] = ['content'=>json_decode($msgTemplate->text_content)];
				// 	if($msgTemplate->other_type == 2){//图片
				// 		$image_url_arr = parse_url($msgTemplate->image_url);
				// 		if($image_url_arr['host'] == $_SERVER["HTTP_HOST"]){
				// 			$msg['image'] = ['media_id'=>$etApp->media->uploadImage('.'.$image_url_arr['path'])['media_id']];
				// 		}else{
				// 			$msg['image'] = ['media_id'=>$etApp->media->uploadImage($msgTemplate->image_url)['media_id']];
				// 		}
				// 	}elseif($msgTemplate->other_type == 3){//图文
				// 		$msg['link'] = [
				// 			'title'=>$msgTemplate->link_title,
				// 			'picurl'=>$msgTemplate->link_picurl,
				// 			'desc'=>$msgTemplate->link_desc,
				// 			'url'=>$msgTemplate->link_url
				// 		];
				// 	}elseif($msgTemplate->other_type == 4){//小程序
				// 		$image_url_arr = parse_url($msgTemplate->miniprogram_picurl);
				// 		if($image_url_arr['host'] == $_SERVER["HTTP_HOST"]){
				// 			$media_id = $etApp->media->uploadImage('.'.$image_url_arr['path'])['media_id'];
				// 		}else{
				// 			$media_id = $etApp->media->uploadImage($msgTemplate->miniprogram_picurl)['media_id'];
				// 		}
				// 		$msg['miniprogram'] = [
				// 			'title'=>$msgTemplate->miniprogram_title,
				// 			'pic_media_id'=>$media_id,
				// 			'appid'=>$msgTemplate->miniprogram_appid,
				// 			'page'=>$msgTemplate->miniprogram_page
				// 		];
				// 	}

				// 	$res = false;
				// 	$msgid = '';
				// 	if($msgTemplate->send_to == 1){
				// 		foreach($externalcontact as $et){
				// 			$external_userids[] = $et['external_userid'];
				// 		}
				// 		$msg['external_userid'] = array_values(array_unique($external_userids));
				// 		if(!$external_userids){
				// 			sendError('没有符合条件的客户');
				// 		}
				// 		$messageRes = $etApp->external_contact_message->submit($msg);
				// 		if($messageRes['errcode'] == 0){
				// 			$res = true;
				// 			$msgid = $messageRes['msgid'];
				// 		}
				// 	}elseif($msgTemplate->send_to == 2){
				// 		foreach($externalcontact as $et){
				// 			if(array_intersect(json_decode($et['tags'],1),json_decode($msgTemplate->send_tag,1))){
				// 				$external_userids[] = $et['external_userid'];
				// 			}
				// 		}
				// 		$msg['external_userid'] = array_values(array_unique($external_userids));
				// 		if(!$external_userids){
				// 			sendError('没有符合条件的客户');
				// 		}
				// 		$messageRes = $etApp->external_contact_message->submit($msg);
				// 		if($messageRes['errcode'] == 0){
				// 			$res = true;
				// 			$msgid = $messageRes['msgid'];
				// 		}
				// 	}elseif($msgTemplate->send_to == 3){
				// 		$msgidList = [];
				// 		foreach(json_decode($msgTemplate->send_user,1) as $user_id){
				// 			$external_userids = array_column((new Model('qy_externalcontact_list'))->field('external_userid')->where(['wid'=>$wid,'user_id'=>$user_id])->list_all_array(), 'external_userid');
				// 			$msg['external_userid'] = $external_userids;
				// 			$user = Helper::getInstance()->get_user_by_id($wid,$user_id);
				// 			$msg['sender'] = $user['userid'];
				// 			$messageRes = $etApp->external_contact_message->submit($msg);
				// 			if($messageRes['errcode'] == 0){
				// 				$res = true;
				// 				$msgidList[] = $messageRes['msgid'];
				// 			}
				// 		}
				// 		$msgid = implode(',', $msgidList);
				// 	}
					
				// 	if($res){
				// 		$msgTemplate->status = 1;
				// 		$msgTemplate->msgid = $msgid;
				// 		$msgTemplate->save();
				// 	}else{
				// 		$msgTemplate->status = 2;
				// 		$msgTemplate->save();
				// 	}
				// }
				sendSuccess('操作成功',[$msgTemplate->id,$msgTemplate->send_mode]); 
			}else{
				sendError('操作失败');
			}
		}
		return $this->show();
	}
	
	public function msg_result(){
		$wid = Session::get('wid');
		if(is_post()){
			setApi();
			$QyWechatApi = QyWechatApi::getInstance();
			$qyConfig = (new Model('qy_wechat_config'))->find(['wid'=>$wid]);
			$etApp = $QyWechatApi->get_qy_app($qyConfig->corp_id,$qyConfig->externalcontact_secret);
			$id = \Request::get(1);
			$msgTemplate = (new Model('qy_et_msg_template'))->find($id);
			$msgids = $msgTemplate->msgid ? explode(',', $msgTemplate->msgid) : [];
			$hasSent = [];
			$hasSentUser = [];
			$notSent = [];
			$notSentUser = [];
			foreach ($msgids as $msgid) {
				if(!$msgid){
					continue;
				}
				$msgResult = $etApp->external_contact_message->get($msgid);
				foreach($msgResult['detail_list'] as $detaillist){
					if($detaillist['status'] == 1 && !in_array($detaillist['external_userid'],$hasSent)){
						$hasSent[] = $detaillist['external_userid'];
						$hasSentUser[] = (new Model('qy_externalcontact_list'))->field("name")->find(['wid'=>$wid,'external_userid'=>$detaillist['external_userid']])->get_model_array();
					}else if($detaillist['status'] == 0 && !in_array($detaillist['external_userid'],$notSent) && !in_array($detaillist['external_userid'],$hasSent)){
						$notSent[] = $detaillist['external_userid'];
						$notSentUser[] = (new Model('qy_externalcontact_list'))->field("name")->find(['wid'=>$wid,'external_userid'=>$detaillist['external_userid']])->get_model_array();
					}
				}
			}
			sendSuccess("成功",[implode(",", array_column($hasSentUser,"name")),implode(",", array_column($notSentUser,"name"))]);
		}
		return $this->show();
	}
	
	public function select_tag(){
		if(\Request::get("id")){
			$this->assign("id",\Request::get("id"));
		}
		$wid = Session::get('wid');
		$etTagArr = (new Model('qy_externalcontact_tag'))->where(['wid'=>$wid])->list_all_array();
		foreach ($etTagArr as $key => $value) {
			$count += count(json_decode($value['tags'],1));
		}
		$this->assign("etTagArr", $etTagArr);
		$this->assign("count",$count);
		return $this->show();
	}
	
	public function update_status_kan(){
		setApi();
		$id = $_POST["id"];
		$contact_way = (new Model('qy_et_contact_way'))->find(['id'=>$id]);
		$contact_way->hyy_status = 1;
		$contact_way->save();
		sendSuccess("修改成功");
	}

	public function update_status_guan(){
		setApi();
		$id = $_POST["id"];
		$contact_way = (new Model('qy_et_contact_way'))->find(['id'=>$id]);
		$contact_way->hyy_status = 0;
		$contact_way->save();
		sendSuccess("修改成功");
	}

	public function select_user(){
		$wid = Session::get('wid');
		$where['wid'] = $wid;
		$where['status'] = 1; 
		$where['is_del@!='] = 1;
		$id = \Request::get(1);
		if($id){
			$contactWay = (new Model('qy_et_contact_way'))->find($id);
			$users = json_decode($contactWay->users,1);
		}
		$userList = (new Model('qy_user_list'))->where($where)->list_all_array();
		$this->assign("users", $users);
		$this->assign("userList", $userList);
		$this->assign("count", count($userList));
		$this->assign("username", \Request::get('username'));
		return $this->show();
	}
	
	public function select_group_chat(){
		$wid = Session::get('wid');
		$groupchatList = (new Model('qy_et_groupchat'))->where(['wid'=>$wid])->list_all_array();
		$this->assign("count", count($groupchatList));
		$this->assign("groupchatList", $groupchatList);
		return $this->show();
	}
	
	public function contact_way(){
		$wid = Session::get('wid');
		$contactWay = new Model('qy_et_contact_way');
		//name 模糊查询
		$name = $_GET['name'];
		$where['wid'] = $wid;
		$where['is_auto_pull_group'] = 0;
		$p = new \Pagination();	
		$h = Helper::getInstance();	
		// $res = $p->model_list($contactWay->where($where)->order('id desc'));
		$sql = "select * from qvmh_qy_et_contact_way where wid={$wid} and is_auto_pull_group=0";
		// $sqls = "select count(*) from qvmh_qy_et_contact_way where wid={$wid} and is_auto_pull_group=0";
		$h = Helper::getInstance(); 
		$page = \Request::get('page');
		$pagesize = 10;
		if($page){
			$pages = $page*$pagesize;
		}else{
			$pages = 0;
			$page = 0;
		}
		$r_user_id_arr = $h->get_check_range('et_data');
		if($r_user_id_arr){
			foreach ($r_user_id_arr as $key => $value) {
				$sql_arr[] = "users like '%\"{$value}\"%'";
				// $sql_arrs[] = "users like '%\"{$value}\"%'";
			}
			$sql .= " and (".implode(' or ', $sql_arr) . ")";
			// $sqls .= " and (".implode(' or ', $sql_arrs) . ")";
		}
		if(trim($name)!=''){
			$sql .= " and name like '%{$name}%'";
			// $sqls .= " and name like '%{$name}%'";
		}
		$sql .= " ORDER BY id DESC";
		// $res = db_query($sql);
		$p = new \Pagination();	
		$res = $p->sql_list($sql);
		// dump($res);die;
		// $count = db_query($sqls);
		// $counts = ceil($count[0]["count(*)"]/$pagesize);
		foreach ($res as $key => $value) {
			$res[$key]['users'] = json_decode($value['users'],1);
			if($value['merge_qr_code']){
				$res[$key]['merge_qr_code'] = $value['merge_qr_code']."?a=".time();
			}
		}
		// dump($count);die;
		/**$h = Helper::getInstance();
		$startDate = date('Y-m-d', strtotime('-1 week'));
		$endDate = date('Y-m-d', strtotime('-1 day'));
		$dateRange = $h->getDateRange($startDate,$endDate);
		$statistics_date = json_encode($dateRange);
		$statistics_data = [];
		foreach($dateRange as $dates){
			$add_num = (new Model('qy_et_contact_way_statistics'))->where(['wid'=>$wid,'ctime'=>strtotime($dates)])->sum('add_num');
			$statistics_data[] = $add_num?$add_num:0;
		}
		//近一周各渠道新增客户数
		$week_add_num = (new Model('qy_et_contact_way_statistics'))->where(
		[
			'wid'      => $wid,
			'ctime@>=' => strtotime($startDate),
			'ctime@<=' => strtotime($endDate),
		])->sum('add_num');*/
		$this->assign("p", $p);
		$this->assign("P", $GLOBALS['P']);
		$this->assign("res", $res);
		// $this->assign("count", $count);
		// $this->assign("counts", $counts);
		$this->assign("page", $page);
		$this->assign("name", $name);
		$this->assign("h", Helper::getInstance());
		/**$this->assign("startDate", $startDate);
		$this->assign("endDate", $endDate);
		$this->assign("statistics_date", $statistics_date);
		$this->assign("statistics_data", json_encode($statistics_data));
		$this->assign("week_add_num", $week_add_num?$week_add_num:0);*/
		return $this->show();
	}

	public function contact_way_statistics(){
		// $wid = Session::get('wid');
		// $h = Helper::getInstance();
		// $startDate = date('Y-m-d', strtotime('-1 week'));
		// $endDate = date('Y-m-d', strtotime('-1 day'));
		// $dateRange = $h->getDateRange($startDate,$endDate);
		// $statistics_date = json_encode($dateRange);
		// $statistics_data = [];
		// foreach($dateRange as $dates){
		// 	$add_num = (new Model('qy_et_contact_way_statistics'))->where(['wid'=>$wid,'ctime'=>strtotime($dates)])->sum('add_num');
		// 	$statistics_data[] = $add_num?$add_num:0;
		// }
		// //近一周各渠道新增客户数
		// $week_add_num = (new Model('qy_et_contact_way_statistics'))->where(
		// [
		// 	'wid'      => $wid,
		// 	'ctime@>=' => strtotime($startDate),
		// 	'ctime@<=' => strtotime($endDate),
		// ])->sum('add_num');

		// $this->assign("startDate", $startDate);
		// $this->assign("endDate", $endDate);
		// $this->assign("statistics_date", $statistics_date);
		// $this->assign("statistics_data", json_encode($statistics_data));
		// $this->assign("week_add_num", $week_add_num?$week_add_num:0);
		return $this->show();
	}
	
	public function download_qrcode(){
		$id = \Request::get(1);
		$contactWay = (new Model('qy_et_contact_way'))->find($id);
		//设置头信息
		if($contactWay->merge_qr_code){
			$h = Helper::getInstance();
			$code = '.'.$contactWay->merge_qr_code;
		}else{
			$code = $contactWay->qr_code;
		}
		header('Content-Disposition:attachment;filename='.$contactWay->name.'.png');
		header('Content-Length:' . filesize($code));
		//读取文件并写入到输出缓冲
		readfile($code);
	}
	
	public function get_contact_way_statistics(){
		setApi();
		$wid = Session::get('wid');
		$h = Helper::getInstance();
		if($_POST['type']){
			if($_POST['type'] == 'one_week'){
				$startDate = date('Y-m-d', strtotime('-1 week'));
				$endDate = date('Y-m-d', strtotime('-1 day'));
			}elseif($_POST['type'] == 'two_week'){
				$startDate = date('Y-m-d', strtotime('-2 week'));
				$endDate = date('Y-m-d', strtotime('-1 day'));
			}elseif($_POST['type'] == 'one_month'){
				$startDate = date('Y-m-d', strtotime('-1 month'));
				$endDate = date('Y-m-d', strtotime('-1 day'));
			}
		}else{
			$startDate =  $_POST['startDate'];
			$endDate = $_POST['endDate'];
		}
		
		$dateRange = $h->getDateRange($startDate,$endDate);
		$statistics_date = $dateRange;
		$statistics_data = [];
		foreach($dateRange as $dates){
			$add_num = (new Model('qy_et_contact_way_statistics'))->where(['wid'=>$wid,'ctime'=>strtotime($dates)])->sum('add_num');
			$statistics_data[] = $add_num?$add_num:0;
		}
		$data = [
			'startDate'=>$startDate,
			'endDate'=>$endDate,
			'statistics_date'=>$statistics_date,
			'statistics_data'=>$statistics_data,
		];
		sendSuccess('获取成功',$data);
	}
	 
	public function add_contact_way(){
		$wid = Session::get('wid');
		$QyWechatApi = QyWechatApi::getInstance();
		$qyConfig = (new Model('qy_wechat_config'))->find(['wid'=>$wid]);
    	$redguest  = (new Model("qy_redguest"))->where(["wid"=>$wid])->list_all();
		$etApp = $QyWechatApi->get_qy_app($qyConfig->corp_id,$qyConfig->externalcontact_secret);
		$contactWay = new Model('qy_et_contact_way');

		//点大
		$sc_point_set = (new Model('sc_point_set'))->find(['wid'=>$wid]);
		$pb_exist = false;
		$pbCoupons = [];
		$pbLevels = [];
		if($sc_point_set->id){
			$pb_exist = true;
			$pbCoupons = (new SyncPointBigData())->selectCoupon($sc_point_set->da_id);
			$pbLevels = (new SyncPointBigData())->selectLevel($sc_point_set->da_id);
		}

		if(is_post()){
			setApi();
			if(!$_POST['checkUser']){
				sendError('请添加使用人员');
			}
			if($_POST['auto_label'] && !$_POST['checkLable']){
				sendError('请添加标签');
			}
			$users = explode(',',$_POST['checkUser']);

			if(count($users) == 1){
				$type = 1;
			}elseif(count($users) > 1){
				$type = 2;
			}
			$scene = 2;//2-通过二维码联系
			$maxId = (new Model('qy_et_contact_way'))->max('id');
			$state = $maxId + 1;//企业自定义的state参数，用于区分不同的添加渠道
			$config = [
			   'remark' => $_POST['bz'],//联系方式的备注信息
			   'skip_verify' => $_POST['skip_verify']?true:false,//外部客户添加时是否无需验证
			   'state' => $state,
			   // 'user' => $users,
			   'user' => Helper::get_userid($users),
			];
			$createRes = QyWechatApi::getInstance()->add_contact_way($type, $scene, $config);
			if($createRes['errcode'] == 0){
				$config_id = $createRes['config_id'];
				$getContactWay = $etApp->contact_way->get($config_id)['contact_way'];
				$contactWay->wid = $wid;
				$contactWay->name = $_POST['name'];
				$contactWay->skip_verify = $_POST['skip_verify'];
				$contactWay->state = $state;
				$contactWay->users = json_encode($users,320);
				$contactWay->type = $type;
				$contactWay->bz = $_POST['bz'];
				$contactWay->config_id = $config_id; 
				$contactWay->qr_code = $getContactWay['qr_code'];
				$contactWay->auto_label = $_POST['auto_label']?1:0;
				$contactWay->select_label = json_encode(explode(',',$_POST['checkLable']),320);
				$contactWay->auto_welcome_msg = $_POST['auto_welcome_msg']?1:0;
				if($contactWay->auto_welcome_msg){
					$hyy_data = [];
					for ($is=0; $is < $_POST["part_time_counts"]; $is++) { 
						$con = $is+1;
						if($_POST["part_time_other_types".$con] == 1){
							continue;
						}else if($_POST["part_time_other_types".$con] == 2){
							$hyy_data[$is]['image'] = $_POST["image".$con];
							// $hyy_data[$is]['image_media_id'] = $etApp->media->uploadImage($this->ste_url($_POST['image'.$con]))["media_id"];
						}else if($_POST["part_time_other_types".$con] == 3){
							$hyy_data[$is]['link_title'] = $_POST["link_title".$con];
							$hyy_data[$is]['link_url'] = $_POST["link_url".$con];
							$hyy_data[$is]['link_pic'] = $_POST["link_pic".$con];
							$hyy_data[$is]['link_desc'] = $_POST["link_desc".$con];
							// $hyy_data[$is]['image_media_id'] = $etApp->media->uploadImage($this->ste_url($_POST['link_pic'.$con]))["media_id"];
						}else if($_POST["part_time_other_types".$con] == 4){
							$hyy_data[$is]['miniprogram_title'] = $_POST["miniprogram_title".$con];
							$hyy_data[$is]['miniprogram_name'] = $_POST["miniprogram_name".$con];
							$hyy_data[$is]['miniprogram_page'] = $_POST["miniprogram_page".$con];
							$hyy_data[$is]['miniprogram_pic'] = $_POST["miniprogram_pic".$con];
							$hyy_data[$is]['miniprogram_appid'] = $_POST["miniprogram_appid".$con];
							// $hyy_data[$is]['image_media_id'] = $etApp->media->uploadImage($this->ste_url($_POST['miniprogram_pic'.$con]))["media_id"];
						}else if($_POST["part_time_other_types".$con] == 5){
							$hyy_data[$is]['red_id'] = $_POST["part_time_otype_reds".$con];
						}
						$hyy_data[$is]["type"] = $_POST["part_time_other_types".$con];
					}
					$contactWay->status = 2;
				}
				$contactWay->text_content = json_encode($_POST['text_content']);
				$contactWay->data = json_encode($hyy_data,320);
				$contactWay->ctime = date('Y-m-d H:i:s');
				$contactWay->dayparting_status = $_POST['part_time_welcome_msg'] ? 1 : 0;
				if($contactWay->dayparting_status == 1){
					$dayparting_data = [];
					$part_time_count = $_POST['part_time_count'];
					for ($i=0; $i < $part_time_count; $i++) {
						$j = $i+1;
						$dayparting_data[$i]['part_time_day'] = $_POST["part_time_day".$j];
						$dayparting_data[$i]['part_time_moment'] = $_POST["part_time_moment".$j];
						$dayparting_data[$i]['part_time_text'] = $_POST["part_time_text".$j];
						$dayparting_data[$i]['part_time_other_type'] = $_POST["part_time_other_type".$j];
						if($_POST["part_time_other_type".$j] == 1){

						}else if($_POST["part_time_other_type".$j] == 2){
							$dayparting_data[$i]['part_time_otype_img'] = $_POST["part_time_otype_img".$j];
							// $dayparting_image_url_arr = explode("/", $_POST["part_time_otype_img".$j]);
							// $dayparting_data[$i]['part_time_otype_img_media_id'] = $etApp->media->uploadImage($this->ste_url($_POST['part_time_otype_img'.$j]))["media_id"];
						}else if($_POST["part_time_other_type".$j] == 3){
							$dayparting_data[$i]['part_time_otype_it_ltitle'] = $_POST["part_time_otype_it_ltitle".$j];
							$dayparting_data[$i]['art_time_otype_it_lurl'] = $_POST["art_time_otype_it_lurl".$j];
							$dayparting_data[$i]['part_time_otype_it_lpic'] = $_POST["part_time_otype_it_lpic".$j];
							$dayparting_data[$i]['part_time_otype_it_ldesc'] = $_POST["part_time_otype_it_ldesc".$j];
						}else if($_POST["part_time_other_type".$j] == 4){
							$dayparting_data[$i]['part_time_otype_mp_name'] = $_POST["part_time_otype_mp_name".$j];
							$dayparting_data[$i]['part_time_otype_mp_appid'] = $_POST["part_time_otype_mp_appid".$j];
							$dayparting_data[$i]['part_time_otype_mp_path'] = $_POST["part_time_otype_mp_path".$j];
							$dayparting_data[$i]['part_time_otype_mp_title'] = $_POST["part_time_otype_mp_title".$j];	
							$dayparting_data[$i]['part_time_otype_mp_pic'] = $_POST["part_time_otype_mp_pic".$j];
							// $dayparting_data[$i]['part_time_otype_mp_img_media_id'] = $etApp->media->uploadImage($this->ste_url($_POST['part_time_otype_mp_pic'.$j]))["media_id"];
						}else if($_POST["part_time_other_type".$j] == 5){
							$dayparting_data[$i]['part_time_otype_red'] = $_POST["part_time_otype_red".$j];
						}
					}
					$contactWay->dayparting_data = json_encode($dayparting_data,320);
				}

				if($pb_exist){
					$contactWay->pb_coupon_status = $_POST['pb_coupon_status']?1:0;
					$contactWay->pb_coupon_id = $_POST['pb_coupon_id'];
					$contactWay->pb_coupon_num = $_POST['pb_coupon_num'];

					$contactWay->pb_setlevel_status = $_POST['pb_setlevel_status']?1:0;
					$contactWay->pb_setlevel_id = $_POST['pb_setlevel_id'];

				}

				$contactWay->save();
				if($_POST['img']){
					$contactWay->merge_qr_code = self::createPoster($contactWay->id,substr($_POST['img'], 1));
					$contactWay->save();
				}
				sendSuccess('操作成功');
			}else{
				sendError('操作失败');
			}
		}
		

		$this->assign("pb_exist", $pb_exist);
		$this->assign("pbLevels", $pbLevels);
		$this->assign("pbCoupons", $pbCoupons);
		$this->assign("contactWay", $contactWay);
		$this->assign("redguest", $redguest);
		return $this->show();
	}

	public function add_file(){
        setApi(); 
        $path = './images';
        $field = 'file';
        if (!$_FILES[$field]) sendError('文件不存在');
        $ext = explode('.', $_FILES[$field]["name"]);
        $ext = $ext[count($ext) - 1];
        if (strtolower($ext) != 'png' && strtolower($ext) != 'jpg') {
            sendError('请上传正确格式的图片');
        }
        // 创建文件夹
        try {
            mkdir($path, 0777, true);
        } catch (\Exception $e) {
            // 防止文件夹已存在
        }
        // $path = $path . '/' . $_FILES['file']['name'];
	    $path = $path . '/' . md5_file($_FILES[$field]['tmp_name']) . '.' . $ext;
        $saveImg = move_uploaded_file($_FILES[$field]['tmp_name'], $path);
        if($saveImg){
            $filePath = $saveImg ? $path : $saveImg;
            $str=ltrim($filePath,".");
            sendSuccess('上传成功',['filePath'=>$str,'fileName'=>$_FILES[$field]["name"]]);
        }else{
            sendError('上传失败');
        }
    } 
	
	public function edit_contact_way(){
		$wid = Session::get('wid');
		$QyWechatApi = QyWechatApi::getInstance();
		$qyConfig = (new Model('qy_wechat_config'))->find(['wid'=>$wid]);
    	$redguest  = (new Model("qy_redguest"))->where(["wid"=>$wid])->list_all();
		$etApp = $QyWechatApi->get_qy_app($qyConfig->corp_id,$qyConfig->externalcontact_secret);
		$id = \Request::get(1);
		if($id){
			$contactWay = (new Model('qy_et_contact_way'))->find($id);
			$contactWay->text_content = json_decode($contactWay->text_content,1)?:$contactWay->text_content;
			$contactWay->data = json_decode($contactWay->data,1);
			$red_id = (new Model('qy_redguest'))->find(['id'=>$contactWay->red_id]);
			//点大
			$sc_point_set = (new Model('sc_point_set'))->find(['wid'=>$wid]);
			$pb_exist = false;
			$pbCoupons = [];
			$pbLevels = [];
			if($sc_point_set->id){
				$pb_exist = true;
				$pbCoupons = (new SyncPointBigData())->selectCoupon($sc_point_set->da_id);
				$pbLevels = (new SyncPointBigData())->selectLevel($sc_point_set->da_id);
			}
		}else{
			die('缺少必要参数');
		}
		if(is_post()){
			setApi();
			if(!$_POST['checkUser']){
				sendError('请添加使用人员');
			}
			if($_POST['auto_label'] && !$_POST['checkLable']){
				sendError('请添加标签');
			}
			if($_POST['img'] && $_POST['img'] != $contactWay->merge_qr_code){
				$contactWay->merge_qr_code = self::createPoster($contactWay->id,substr($_POST['img'], 1));
			}
			$contactWay->name = $_POST['name'];
			$contactWay->auto_label = $_POST['auto_label']?1:0;
			$contactWay->select_label = json_encode(explode(',',$_POST['checkLable']),320);
			$contactWay->auto_welcome_msg = $_POST['auto_welcome_msg']?1:0;
			if($contactWay->auto_welcome_msg){
				$hyy_data = [];
				for ($is=0; $is < $_POST["part_time_counts"]; $is++) { 
					$con = $is+1;
					if($_POST["part_time_other_types".$con] == 1){
						continue;
					}else if($_POST["part_time_other_types".$con] == 2){
						$hyy_data[$is]['image'] = $_POST["image".$con];
						// $hyy_data[$is]['image_media_id'] = $etApp->media->uploadImage($this->ste_url($_POST['image'.$con]))["media_id"];
					}else if($_POST["part_time_other_types".$con] == 3){
						$hyy_data[$is]['link_title'] = $_POST["link_title".$con];
						$hyy_data[$is]['link_url'] = $_POST["link_url".$con];
						$hyy_data[$is]['link_pic'] = $_POST["link_pic".$con];
						$hyy_data[$is]['link_desc'] = $_POST["link_desc".$con];
						// $hyy_data[$is]['image_media_id'] = $etApp->media->uploadImage($this->ste_url($_POST['link_pic'.$con]))["media_id"];
					}else if($_POST["part_time_other_types".$con] == 4){
						$hyy_data[$is]['miniprogram_title'] = $_POST["miniprogram_title".$con];
						$hyy_data[$is]['miniprogram_name'] = $_POST["miniprogram_name".$con];
						$hyy_data[$is]['miniprogram_page'] = $_POST["miniprogram_page".$con];
						$hyy_data[$is]['miniprogram_pic'] = $_POST["miniprogram_pic".$con];
						$hyy_data[$is]['miniprogram_appid'] = $_POST["miniprogram_appid".$con];
						// $hyy_data[$is]['image_media_id'] = $etApp->media->uploadImage($this->ste_url($_POST['miniprogram_pic'.$con]))["media_id"];
					}else if($_POST["part_time_other_types".$con] == 5){
						$hyy_data[$is]['red_id'] = $_POST["part_time_otype_reds".$con];
					}
					$hyy_data[$is]["type"] = $_POST["part_time_other_types".$con];
				}
			}
			$contactWay->status = 2;
			$contactWay->text_content = json_encode($_POST['text_content']);
			$contactWay->data = json_encode($hyy_data,320);
			$contactWay->dayparting_status = $_POST['part_time_welcome_msg'] ? 1 : 0;
				if($contactWay->dayparting_status == 1){
					$dayparting_data = [];
					$part_time_count = $_POST['part_time_count'];
					for ($i=0; $i < $part_time_count; $i++) {
						$j = $i+1;
						$dayparting_data[$i]['part_time_day'] = $_POST["part_time_day".$j];
						$dayparting_data[$i]['part_time_moment'] = $_POST["part_time_moment".$j];
						$dayparting_data[$i]['part_time_text'] = $_POST["part_time_text".$j];
						$dayparting_data[$i]['part_time_other_type'] = $_POST["part_time_other_type".$j];
						if($_POST["part_time_other_type".$j] == 1){

						}else if($_POST["part_time_other_type".$j] == 2){
							$dayparting_data[$i]['part_time_otype_img'] = $_POST["part_time_otype_img".$j];
							// $dayparting_image_url_arr = explode("/", $_POST["part_time_otype_img".$j]);
							// $dayparting_data[$i]['part_time_otype_img_media_id'] = $etApp->media->uploadImage($this->ste_url($_POST['part_time_otype_img'.$j]))["media_id"];
						}else if($_POST["part_time_other_type".$j] == 3){
							$dayparting_data[$i]['part_time_otype_it_ltitle'] = $_POST["part_time_otype_it_ltitle".$j];
							$dayparting_data[$i]['art_time_otype_it_lurl'] = $_POST["art_time_otype_it_lurl".$j];
							$dayparting_data[$i]['part_time_otype_it_lpic'] = $_POST["part_time_otype_it_lpic".$j];
							$dayparting_data[$i]['part_time_otype_it_ldesc'] = $_POST["part_time_otype_it_ldesc".$j];
						}else if($_POST["part_time_other_type".$j] == 4){
							$dayparting_data[$i]['part_time_otype_mp_name'] = $_POST["part_time_otype_mp_name".$j];
							$dayparting_data[$i]['part_time_otype_mp_appid'] = $_POST["part_time_otype_mp_appid".$j];
							$dayparting_data[$i]['part_time_otype_mp_path'] = $_POST["part_time_otype_mp_path".$j];
							$dayparting_data[$i]['part_time_otype_mp_title'] = $_POST["part_time_otype_mp_title".$j];	
							$dayparting_data[$i]['part_time_otype_mp_pic'] = $_POST["part_time_otype_mp_pic".$j];
							// $dayparting_pic_arr = explode("/", $_POST["part_time_otype_mp_pic".$j]);
							// $dayparting_data[$i]['part_time_otype_mp_img_media_id'] = $etApp->media->uploadImage($this->ste_url($_POST['part_time_otype_mp_pic'.$j]))["media_id"];
						}else if($_POST["part_time_other_type".$j] == 5){
							$dayparting_data[$i]['part_time_otype_red'] = $_POST["part_time_otype_red".$j];
						}
					}
					$contactWay->dayparting_data = json_encode($dayparting_data);
				}

			if($pb_exist){
				$contactWay->pb_coupon_status = $_POST['pb_coupon_status']?1:0;
				$contactWay->pb_coupon_id = $_POST['pb_coupon_id'];
				$contactWay->pb_coupon_num = $_POST['pb_coupon_num'];

				$contactWay->pb_setlevel_status = $_POST['pb_setlevel_status']?1:0;
				$contactWay->pb_setlevel_id = $_POST['pb_setlevel_id'];

			}
			$contactWay->save();
			
			$users = explode(',',$_POST['checkUser']);
			$configId = $contactWay->config_id;
			$config = [
			   'remark' => $_POST['bz'],
			   'skip_verify' => $_POST['skip_verify']?true:false,
			   'user' => Helper::get_userid($users)
			];
			$updateRes = $etApp->contact_way->update($configId, $config);
			if($updateRes['errcode'] == 0){
				$getContactWay = $etApp->contact_way->get($contactWay->config_id)['contact_way'];
				$contactWay->skip_verify = $_POST['skip_verify'];
				$contactWay->users = json_encode($users,320);
				$contactWay->bz = $_POST['bz'];
				$contactWay->qr_code = $getContactWay['qr_code'];
				$contactWay->save();
				sendSuccess('操作成功');
			}else{
				sendError('操作失败');
			}
		}

		if($contactWay->dayparting_status == 1){
			$contactWay->dayparting_data = json_decode($contactWay->dayparting_data,1);
		}
		if($contactWay->merge_qr_code){
			$contactWay->merge_qr_codes = $contactWay->merge_qr_code."?a=".time();
		}
		$this->assign("redguest", $redguest);
		$this->assign("pb_exist", $pb_exist);
		$this->assign("pbLevels", $pbLevels);
		$this->assign("pbCoupons", $pbCoupons);
		$this->assign("red_id", $red_id);
		$this->assign("contactWay", $contactWay);
		$this->assign("h", Helper::getInstance());
		return $this->show();
	}
	
	public function del_contact_way(){
		setApi();
		$wid = $this->wid;
		$QyWechatApi = QyWechatApi::getInstance();
		$qyConfig = (new Model('qy_wechat_config'))->find(['wid'=>$wid]);
		$etApp = $QyWechatApi->get_qy_app($qyConfig->corp_id,$qyConfig->externalcontact_secret);
		$id = $_POST['id'];
		if($id){
			$contactWay = (new Model('qy_et_contact_way'))->find($id);
		}else{
			sendError('参数错误');
		}
		$configId = $contactWay->config_id;
		$deleteRes = $etApp->contact_way->delete($configId);
		if($deleteRes['errcode'] == 0){
			$contactWay->delete();
			sendSuccess('操作成功');
		}else{
			sendError('操作失败 '.$deleteRes['errmsg']);
		}
		
	}
	
	public function contact_way_statistic(){
		return $this->show();
	}
	
	public function del_follow_user_record(){
		$wid = Session::get('wid');
		$record = new Model('qy_del_follow_user_record');
		$h = Helper::getInstance(); 
		$etTagArr = $h->get_et_tags($wid);
		$r_user_id_arr = $h->get_check_range('et_data');
		if($r_user_id_arr){
			$where['user_id'] = $r_user_id_arr;
		}
		$where['wid'] = $wid;
		$p = new \Pagination();		
		$res = $p->model_list($record->where($where)->order('id desc'));
		foreach($res as $k=>$v){
			$et = (new Model('qy_externalcontact_list'))->find(['wid'=>$v->wid,'user_id'=>$v->user_id,'external_userid'=>$v->external_userid]);
			$res[$k]->tags = json_decode($et->tags_info,1);
		}
		$this->assign("etTagArr", $etTagArr);
		$this->assign("p", $p);
		$this->assign("P", $GLOBALS['P']);
		$this->assign("res", $res);
		$this->assign("h", Helper::getInstance());
		return $this->show();
	}

	/**
	*  获取渠道活码列表信息
	**/
	public function contact_way_list(){
		setApi();
		$wid = $this->wid;
		$contactWay = new Model('qy_et_contact_way');
		$id = \Request::get("id");
		if($id){
			$res = $contactWay->find($id)->get_model_array();
			if(!$res['id']){
				sendError('此数据不存在');
			}
			$res['select_label'] = json_decode($res['select_label'],1);
			$res['users'] = json_decode($res['users'],1);
			sendSuccess('单条渠道活码',$res);
		}
		//name 模糊查询
		// $name = $_GET['name'];
		// if(trim($name)!=''){
		// 	$where['name@~'] = $name;
		// }
		$where['wid'] = $wid;
		$where['is_auto_pull_group'] = 0;
		$res = $contactWay->field('id,wid,name,state,qr_code,users,type,bz,ctime')->where($where)->order('id desc')->list_all_array();
		foreach($res as $k=>$v){
			$user = json_decode($v['users'],1);
			$res[$k]['users'] = $user;
			$res[$k]['ischeck'] = true;
		}
		sendSuccess('渠道活码列表信息',$res);
	}
	/**
	*  人数统计
	**/
	public function get_contact_way_peocount(){
		setApi();
		$wid = $this->wid;
		$peocount = [
			'today_num' => 0,
			'today_delnum' => 0,
			'total_num' => 0,
			'total_delnum' => 0,

		];
		$users  = [];
		$contact_way = (new Model('qy_et_contact_way'))->where(['wid'=>$wid])->order("id desc")->list_all_array();
		// dump($contact_way);die;
		if(!count($contact_way)){
			sendSuccess('无渠道活码',['peocount'=>$peocount,'users'=>$users]);
		}
		// $state_arr = $_POST['state'] ?: explode(',', $contact_way[0]->state);
		$state_arr = $_POST['state'] ?: array_column($contact_way, 'state');
		// $state_arr  = explode(',', $state);
		$user_id_arr = [];
		foreach ($contact_way as $key => $contact) {
			if(in_array($contact['state'], $state_arr)){
				$user_id_arr = array_merge($user_id_arr,json_decode($contact['users'],1));
			}
		}
		$qy_users = (new Model('qy_user_list'))->where(['id'=>$user_id_arr])->list_all();
		foreach ($qy_users as $ku => $qy_user) {
			$users[] = [
				'user_id' => $qy_user->id,
				'name' => $qy_user->name
			];
		}
		$today = strtotime("today");
		$peocount['today_num'] = (new Model('qy_externalcontact_list'))->where(['wid'=>$wid,'state'=>$state_arr,'createtime@>'=>$today])->count();
		$peocount['today_delnum'] = (new Model('qy_externalcontact_list'))->where(['wid'=>$wid,'state'=>$state_arr,'createtime@>'=>$today,'status@!='=>0])->count();
		$peocount['total_num'] = (new Model('qy_externalcontact_list'))->where(['wid'=>$wid,'state'=>$state_arr])->count();
		$peocount['total_delnum'] = (new Model('qy_externalcontact_list'))->where(['wid'=>$wid,'state'=>$state_arr,'status@!='=>0])->count();
		
		sendSuccess('人数统计',['peocount'=>$peocount,'users'=>$users]);
	}
	/**
	*  图标数据
	**/
	public function get_contact_way_etstatistic(){
		setApi();
		$wid = $this->wid;
		$user_statistic = [];
		$date_statistic = [];
		$resultsdata = [];
		$users  = [];
		$contact_way = (new Model('qy_et_contact_way'))->where(['wid'=>$wid])->order("id desc")->list_all();
		// dump($contact_way);die;
		if(!count($contact_way)){
			sendSuccess('无渠道活码数据',['user_statistic'=>$user_statistic,'date_statistic'=>$date_statistic]);
		}
		if(empty($_POST['state']) && $_POST['users']){
			sendError('缺少必要参数');
		}
		$state_arr = $_POST['state'];
		// sendError($_POST['state']);
		$user_id_arr = [];
		if($state_arr){
			// $state_arr = explode(',', $_POST['state']);
			if($_POST['users']){
				$user_id_arr =  json_decode($_POST['users']);
			}else{
				foreach ($contact_way as $contact) {
					if(in_array($contact->state, $state_arr)){
						$user_id_arr = array_merge($user_id_arr,json_decode($contact->users,1));
					}
				}
			}
		}else{
			$state_arr = [];
			foreach ($contact_way as $contact) {
				$state_arr[] = $contact->state;
				$user_id_arr = array_merge($user_id_arr,json_decode($contact->users,1));
			}
			// $state_arr = $contact_way[0]->state;
			// $user_id_arr = json_decode($contact_way[0]->users,1);
		}
		$etStatisticType = $_POST['etStatisticType'] ?: 'totalNum';
		$dateType = $_POST['dateType'] ?: 'week';
		switch ($dateType) {
			case 'day':
				$start_time = strtotime("today");
				$end_time = $start_time + (24*3600-1);
				break;
			case 'week':
				$start_time = strtotime(date('Y-m-d',strtotime('-6 day')));
				// echo date("Y-m-d H:i:s", $start_time).'<br>';
				// echo $start_time;
				$end_time = strtotime('now');
				break;
			case 'month':
				$start_time = strtotime(date('Y-m-d',strtotime('-29 day')));
				$end_time = strtotime('now');
				break;
			case 'custom':
				if(!$_POST['startDate'] && !$_POST['startDate']){
					sendError('缺少必要参数');
				}
				$start_time = strtotime($_POST['startDate']);
				$end_time = strtotime($_POST['endDate'])+(24*3600);
				break;
			default:
				$start_time = strtotime(date('Y-m-d',strtotime('-6 day')));
				$end_time = strtotime('now');
				break;
		}
		$count_day = ceil(($end_time - $start_time)/(24*3600));
		
		$qy_users = (new Model('qy_user_list'))->where(['id'=>$user_id_arr])->list_all();
		//按日期查
		$start_et_count = (new Model('qy_externalcontact_list'))->where(['wid'=>$wid,'state'=>$state_arr,'createtime@<'=>$start_time,'user_id'=>$user_id_arr])->count();
		$et = (new Model('qy_externalcontact_list'))->where(['wid'=>$wid,'state'=>$state_arr,'createtime@>'=>$start_time,'createtime@<'=>$end_time,'user_id'=>$user_id_arr])->list_all();
		// $time = $start_time;
		$total_num = $start_et_count;
		for ($i=0; $i < $count_day; $i++) {
			$time = 0;
			$time = $start_time+($i*24*3600);
			$today_new = 0;
			$total_del = (new Model('qy_externalcontact_list'))->where(['wid'=>$wid,'state'=>$state_arr,'deltime@>'=>$time,'deltime@<'=>$time + (24*3600),'user_id'=>$user_id_arr])->count();
			foreach ($et as $v) {
				if($v->createtime > $time && $v->createtime < $time + (24*3600)){
					$today_new = $today_new + 1;
				}
			}
			$total_num = $total_num + $today_new;
			$date_statistic[] = [
				'date' => date('Y-m-d',$time),
				'total_num' => $total_num,
				'day_new' => $today_new,
				'day_del' => $total_del,
			];
			if($etStatisticType == 'totalNum'){
				$resultsdata['number'][] = $total_num;
			}else if($etStatisticType == 'todayNew'){
				$resultsdata['number'][] = $today_new;
			}else if($etStatisticType == 'totayDel'){
				$resultsdata['number'][] = $total_del;
			}
			$resultsdata['date'][] = date('Y-m-d',$time);
		}
		$mode = $_POST['mode'] ?: 'date';
		if($mode == 'users'){ 
			//按员工查
			for ($i=0; $i < count($qy_users); $i++) { 
				$user_statistic[] = [
					// 'id' => $qy_users[$i]->id,
					// 'avatar' => $qy_users[$i]->avatar,
					'name' =>  $qy_users[$i]->name,
					'total_num' => (new Model('qy_externalcontact_list'))->where(['wid'=>$wid,'state'=>$state_arr,'createtime@<'=>$end_time,'user_id'=>$qy_users[$i]->id])->count(),
					'day_new' => (new Model('qy_externalcontact_list'))->where(['wid'=>$wid,'state'=>$state_arr,'createtime@>'=>$start_time,'createtime@<'=>$end_time,'user_id'=>$qy_users[$i]->id])->count(),
					'day_del' => (new Model('qy_externalcontact_list'))->where(['wid'=>$wid,'state'=>$state_arr,'deltime@>'=>$start_time,'deltime@<'=>$end_time,'user_id'=>$qy_users[$i]->id,'status@!='=>0])->count(),
				];
			}
			sendSuccess('图表数据统计',['type'=>'users','users'=>$_POST['users'],'etStatisticType'=>$etStatisticType,'linedata'=>$resultsdata,'users_statistic'=>$user_statistic]);
		}
			sendSuccess('图表数据统计',['type'=>'date','users'=>$_POST['users'],'etStatisticType'=>$etStatisticType,'linedata'=>$resultsdata,'date_statistic'=>$date_statistic]);

	}
	/**
	*InterfaceDoc 渠道活码 添加 接口
	*/
	public function contact_way_add(){
		setApi();
		$wid = $this->wid;
		$QyWechatApi = QyWechatApi::getInstance();
		$qyConfig = (new Model('qy_wechat_config'))->find(['wid'=>$wid]);
    	$redguest  = (new Model("qy_redguest"))->where(["wid"=>$wid])->list_all();
		$etApp = $QyWechatApi->get_qy_app($qyConfig->corp_id,$qyConfig->externalcontact_secret);
		$contactWay = new Model('qy_et_contact_way');

		if(!is_post()){
			sendError('非POST提交',4);
		}
		if(!$_POST['users']){
				sendError('请添加使用人员',5);
		}
		if($_POST['auto_label'] && !$_POST['select_label']){
			sendError('请添加标签',6);
		}
		$users = explode(',',$_POST['users']);

		if(count($users) == 1){
			$type = 1;
		}elseif(count($users) > 1){
			$type = 2;
		}

		$scene = 2;//2-通过二维码联系
		$maxId = (new Model('qy_et_contact_way'))->max('id');
		$state = $maxId + 1;//企业自定义的state参数，用于区分不同的添加渠道
		// sendError(json_encode(Helper::get_userid($users)));
		$config = [
		   'remark' => $_POST['bz'],//联系方式的备注信息
		   'skip_verify' => $_POST['skip_verify']?true:false,//外部客户添加时是否无需验证
		   'user' => Helper::get_userid($users),
		];
		$id = $_POST['id'];
		if($id){
			$contactWay->find($id);
			if(!$contactWay->id){
				sendError('参数错误',7);
			}
			$config_id = $contactWay->config_id;
			$Res = $etApp->contact_way->update($config_id, $config);
		}else{
			$config['state'] =  $state;
			$Res = $etApp->contact_way->create($type, $scene, $config);
			$config_id = $Res['config_id'];
			$contactWay->config_id = $config_id;
			$contactWay->state = $state;
			$contactWay->type = $type;
			$contactWay->ctime = date('Y-m-d H:i:s');
		}
		if($Res['errcode'] == 0){
			$getContactWay = $etApp->contact_way->get($config_id)['contact_way'];
			$contactWay->qr_code = $getContactWay['qr_code'];
			$contactWay->wid = $wid;
			$contactWay->name = $_POST['name'];
			$contactWay->skip_verify = $_POST['skip_verify'];
			$contactWay->users = json_encode($users,320);
			$contactWay->bz = $_POST['bz'];
			$contactWay->auto_label = $_POST['auto_label']?1:0;
			$contactWay->select_label = json_encode(explode(',',$_POST['select_label']),320);
			$contactWay->auto_welcome_msg = $_POST['auto_welcome_msg']?1:0;
			$contactWay->text_content = $_POST['text_content'];
			$contactWay->other_type = $_POST['other_type'];
			$contactWay->image_url = $_POST['image_url'];
			$image_url_arr = explode("/", $_POST['image']);
			$contactWay->image_media_id = $etApp->media->uploadImage("./tmpImg/{$image_url_arr[count($image_url_arr)-1]}")["media_id"];
			$contactWay->link_title = $_POST['link_title'];
			$contactWay->link_picurl = $_POST['link_picurl'];
			$contactWay->link_desc = $_POST['link_desc'];
			$contactWay->link_url = $_POST['link_url'];
			$contactWay->miniprogram_title = $_POST['miniprogram_title'];
			$contactWay->miniprogram_name = $_POST['miniprogram_name'];
			$contactWay->miniprogram_url = $_POST['miniprogram_url'];
			$miniprogram_pic_arr = explode("/", $_POST['miniprogram_url']);
			$contactWay->miniprogram_pic_media_id = $etApp->media->uploadImage("./tmpImg/{$miniprogram_pic_arr[count($miniprogram_pic_arr)-1]}")["media_id"];
			$contactWay->miniprogram_appid = $_POST['miniprogram_appid'];
			$contactWay->miniprogram_page = $_POST['miniprogram_page'];
			$contactWay->red_id = $_POST['interest'];
			$contactWay->dayparting_status = $_POST['dayparting_status'] ? 1:0;
			$contactWay->dayparting_data = $_POST['dayparting_data'];
			$contactWay->save();
			sendSuccess('操作成功');
		}else{
			sendError('操作失败',0);
		}
	}


	public function createPoster($id,$image){
        $wid = \Session::get("wid");
        $code = (new Model("qy_et_contact_way"))->find(["wid"=>$wid,"id"=>$id]);
        $config = array(
            'image'=>array(
                array(
                    'url'=>$image,     //头像
                    'stream'=>0,
                    'left'=>158,
                    'top'=>-158,
                    'right'=>0,
                    'bottom'=>0,
                    'width'=>80,
                    'height'=>80,
                    'opacity'=>100
                )
            ),
            'background'=>$code->qr_code          //二维码
        );
        $filename = 'images/'.$wid."_".$code->id.'.jpg';
        //如果要看报什么错，可以先注释调这个header
        if(empty($filename)) header("content-type: image/png");
        $imageDefault = array(
            'left'=>0,
            'top'=>0,
            'right'=>0,
            'bottom'=>0,
            'width'=>100,
            'height'=>100,
            'opacity'=>100
        );
        $textDefault = array(
            'text'=>'',
            'left'=>0,
            'top'=>0,
            'fontSize'=>32,       //字号
            'fontColor'=>'255,255,255', //字体颜色
            'angle'=>0,
        );
        $background = $config['background'];//海报最底层得背景
        //背景方法
        $backgroundInfo = getimagesize($background);
        $backgroundFun = 'imagecreatefrom'.image_type_to_extension($backgroundInfo[2], false);
        $background = $backgroundFun($background);
        $backgroundWidth = imagesx($background);  //背景宽度
        $backgroundHeight = imagesy($background);  //背景高度
        $imageRes = imageCreatetruecolor($backgroundWidth,$backgroundHeight);
        $color = imagecolorallocate($imageRes, 0, 0, 0);
        imagefill($imageRes, 0, 0, $color);
        // imageColorTransparent($imageRes, $color);  //颜色透明
        imagecopyresampled($imageRes,$background,0,0,0,0,imagesx($background),imagesy($background),imagesx($background),imagesy($background));
        //处理了图片
        if(!empty($config['image'])){
            foreach ($config['image'] as $key => $val) {
                $val = array_merge($imageDefault,$val);
                $info = getimagesize($val['url']);
                $function = 'imagecreatefrom'.image_type_to_extension($info[2], false);
                if($val['stream']){   //如果传的是字符串图像流
                    $info = getimagesizefromstring($val['url']);
                    $function = 'imagecreatefromstring';
                }
                $res = $function($val['url']);
                $resWidth = $info[0];
                $resHeight = $info[1];
                //建立画板 ，缩放图片至指定尺寸
                $canvas=imagecreatetruecolor($val['width'], $val['height']);
                imagefill($canvas, 0, 0, $color);
                //关键函数，参数（目标资源，源，目标资源的开始坐标x,y, 源资源的开始坐标x,y,目标资源的宽高w,h,源资源的宽高w,h）
                imagecopyresampled($canvas, $res, 0, 0, 0, 0, $val['width'], $val['height'],$resWidth,$resHeight);
                $val['left'] = $val['left']<0?$backgroundWidth- abs($val['left']) - $val['width']:$val['left'];
                $val['top'] = $val['top']<0?$backgroundHeight- abs($val['top']) - $val['height']:$val['top'];
                //放置图像
                imagecopymerge($imageRes,$canvas, $val['left'],$val['top'],$val['right'],$val['bottom'],$val['width'],$val['height'],$val['opacity']);//左，上，右，下，宽度，高度，透明度
            }
        }
        //处理文字
        if(!empty($config['text'])){
            foreach ($config['text'] as $key => $val) {
                $val = array_merge($textDefault,$val);
                list($R,$G,$B) = explode(',', $val['fontColor']);
                $fontColor = imagecolorallocate($imageRes, $R, $G, $B);
                $val['left'] = $val['left']<0?$backgroundWidth- abs($val['left']):$val['left'];
                $val['top'] = $val['top']<0?$backgroundHeight- abs($val['top']):$val['top'];
                imagettftext($imageRes,$val['fontSize'],$val['angle'],$val['left'],$val['top'],$fontColor,$val['fontPath'],$val['text']);
            }
        }
        //生成图片
        if(!empty($filename)){
            $res = imagejpeg ($imageRes,$filename,90); //保存到本地
            imagedestroy($imageRes);
            if(!$res) return false;
            return "/".$filename; 
        }else{
            imagejpeg($imageRes);     //在浏览器上显示
            imagedestroy($imageRes);
            return $imageRes;
        }
    }

    public function ste_url($url){
    	if(strpos($url,$_SERVER['HTTP_HOST'])){
    		if(substr($url, 0,5) == 'https'){
    			$url = str_replace("https://".$_SERVER['HTTP_HOST'],".",$url);
    		}else{
    			$url = str_replace("http://".$_SERVER['HTTP_HOST'],".",$url);
    		}
    	}
    	return $url;
    }

}